How to use call_user_func_array with a simple function and with class methods

In this post you will see a example of using call_user_func_array (from PHP) to call a simple function, a public static method from a class and a public method.

First I define one function and one class:

  1. function add($p1, $p2){
  2.    return $p1 + $p2;
  3. }
  4.  
  5. class CSimpleMath{
  6.    function __construct($v1) {      
  7.    }
  8.  
  9.    public static function multiply($a, $b){
  10.       return $a * $b;
  11.    }
  12.  
  13.    public function substract($a, $b){
  14.       return $b$a;
  15.    }
  16.  
  17.    function __destruct() {            
  18.    }   
  19. }

Maybe you notice that in the class I did inserted a construct and destruct functions. You dont realy need them for this example to work but I always include them when I write a class.

Call a simple function with call_user_func_array:

  1. echo call_user_func_array(‘add’, array(2, 5));

Call a public static method:

  1. echo call_user_func_array(‘CSimpleMath::multiply’, array(2, 5));

Call a public class method

  1. call_user_func_array(array(‘CSimpleMath’, ‘substract’), array(2, 5));

Tags: , , , , ,

Comments are closed.