Calling static method via string variable

Discussion in 'PHP' started by Gray Fox, Oct 11, 2009.

  1. #1
    I want to call static method Status::compile() that has it's name stored in a variable like this
    
    $function = "Status::compile";
    
    PHP:
    I tried
    
    $function();
    
    PHP:
    but, as expected, it throws an error Fatal error: Call to undefined function Status::compile().

    Is there any way to do it without using lambda functions (working in PHP 5.2.9) or eval()?
     
    Gray Fox, Oct 11, 2009 IP
  2. premiumscripts

    premiumscripts Peon

    Messages:
    1,062
    Likes Received:
    48
    Best Answers:
    0
    Trophy Points:
    0
    #2
    class Status {
    	static function compile() {
    		echo 'compile';
    	}
    }
    
    $string = "Status::compile";
    
    list($class, $function) = explode('::', $string);
    
    call_user_func(array($class, $function));
    
    PHP:
     
    premiumscripts, Oct 11, 2009 IP
    Gray Fox likes this.
  3. Gray Fox

    Gray Fox Well-Known Member

    Messages:
    196
    Likes Received:
    8
    Best Answers:
    0
    Trophy Points:
    130
    #3
    Excellent, works perfectly, even if i call it directly like
    
    call_user_func("Status::compile");
    
    PHP:
    Thanks, premiumscripts.
     
    Gray Fox, Oct 11, 2009 IP
  4. premiumscripts

    premiumscripts Peon

    Messages:
    1,062
    Likes Received:
    48
    Best Answers:
    0
    Trophy Points:
    0
    #4
    Oh lol, I didn't know that. Thanks for telling me ;)
     
    premiumscripts, Oct 11, 2009 IP
  5. szalinski

    szalinski Peon

    Messages:
    341
    Likes Received:
    5
    Best Answers:
    0
    Trophy Points:
    0
    #5
    how about (notice the quotes are not used)

    $function = Status::compile();
    PHP:
    ?
     
    szalinski, Oct 12, 2009 IP
  6. kbluhm

    kbluhm Peon

    Messages:
    23
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #6
    I am assuming the OP is somehow building a static method name as a string and then would like to execute that method using the string value. The value may change and therefor could not be hard-coded as you have provided in your example.
     
    kbluhm, Oct 12, 2009 IP