How to invoke dynamically a class method in PHP?
How to invoke dynamically a class method in PHP?
Today will talk about calling a method from inside class, however you are in the situation of calling a method dynamically in a loop, for each element of an array. To do this we will make use of a php function called call_user_func
.Using this function, you will be able to solve this issue, and it works for both static and non-static methods.
Example
From PHP documentation we can see bellow php function that can be used for this:
call_user_func
(PHP 4, PHP 5)
call_user_func — Calls the
callback
given by the first parameter and passes the remaining parameters as arguments.
mixed call_user_func ( callable $callback
[, mixed $parameter
[, mixed $...
]] )
This functions is similar with the eval() from javascript.
Sample code
This works for non static functions like this:
1 2 3 4 5 6 |
<?php $objClass = new myClass(); $methodName = 'setSomeField'; call_user_func( array( $objClass, $methodName ), 'params' ); ?> |
The above snippet calls the method ‘setSomeField’ from ‘myClass’ with the third parameter called ‘params’ which is a string in this case. You can pass also an array of parameters, and inside the method you can split them as you want, but for the moment let’s keep it simple.
For static calls you can use the following snippet:
1 2 3 4 5 6 |
<?php call_user_func( array( 'ClassName', 'methodName' ) ); //As of PHP 5.2.3 you can use also this format call_user_func( 'ClassName::methodName' ); ?> |
That’s it for today, will see you again with our next snippet!