Programming PHP How to dynamically call methods in PHP

How to dynamically call methods in PHP

How to dynamically call methods in PHP-techbriefers.com

A simple definition for methods is: Methods are functions encapsulated within a class. Now lets explain how to dynamically call methods.

Sometimes we need to call different methods as per our requirement and conditions. To do so, we can call any method dynamically.

To call a method dynamically means that we can assign method name to any variable and call the method using that variable, either in switch case of if else block or anywhere depending on our requirement. Below is the snippet and code explanation which demonstrate how to call a method dynamically.

Code to call a method dynamically

Code explanation:

Above is a class DynamicCalling which has three methods: caller(), methodOne(), methodTwo().

Purpose of the caller() method is to call other methods by passing their names as argument $to_call. If the method of the name same as the value of $to_call is callable, i.e. available and can be called, then it is called. This validity is checked by is_callable() function of core PHP in which passed $this as object of same class for method reference and $to_call as method name to check valid method of class DynamicCalling.

If you need to call method of any other class, simply replace the $this with object of that class and pass the method name.

Example to call other class method dynamically

Leave a Reply