How to invoke dynamically a class method in PHP?

→ Are you a new visitor? Please visit the page guidance for new visitors ←

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:

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:

That’s it for today, will see you again with our next snippet!

Request an article ←