Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I dynamically invoke a class method in PHP?

Tags:

php

callback

How can I dynamically invoke a class method in PHP? The class method is not static. It appears that

call_user_func(...) 

only works with static functions?

Thanks.

like image 496
mmattax Avatar asked Nov 07 '08 18:11

mmattax


People also ask

How to call class method dynamically in php?

Just replace the class name with TestClass , the method name with $methodName and the method arguments with ... $args . Note that, in the later case, it doesn't matter that the method is static or non-static. One advantage is you can pass the array as a callable to a function.

How do you call a class method in PHP?

When calling a class constant using the $classname :: constant syntax, the classname can actually be a variable. As of PHP 5.3, you can access a static class constant using a variable reference (Example: className :: $varConstant).


2 Answers

It works both ways - you need to use the right syntax

//  Non static call call_user_func( array( $obj, 'method' ) );  //  Static calls call_user_func( array( 'ClassName', 'method' ) ); call_user_func( 'ClassName::method' ); // (As of PHP 5.2.3) 
like image 101
Peter Bailey Avatar answered Oct 05 '22 23:10

Peter Bailey


Option 1

// invoke an instance method $instance = new Instance(); $instanceMethod = 'bar'; $instance->$instanceMethod();  // invoke a static method $class = 'NameOfTheClass'; $staticMethod = 'blah'; $class::$staticMethod(); 

Option 2

// invoke an instance method $instance = new Instance(); call_user_func( array( $instance, 'method' ) );  // invoke a static method $class = 'NameOfTheClass'; call_user_func( array( $class, 'nameOfStaticMethod' ) ); call_user_func( 'NameOfTheClass::nameOfStaticMethod' ); // (As of PHP 5.2.3) 

Option 1 is faster than Option 2 so try to use them unless you don't know how many arguments your going to be passing to the method.


Edit: Previous editor did great job of cleaning up my answer but removed mention of call_user_func_array which is different then call_user_func.

PHP has

mixed call_user_func ( callable $callback [, mixed $parameter [, mixed $... ]] )  

http://php.net/manual/en/function.call-user-func.php

AND

mixed call_user_func_array ( callable $callback , array $param_arr ) 

http://php.net/manual/en/function.call-user-func-array.php

Using call_user_func_array is orders of magnitude slower then using either option listed above.

like image 41
David Avatar answered Oct 06 '22 00:10

David