How to call a custom method from a class

There are some cases when you don’t know the name of a function you need to call, or that name can depend from various cases. This is why you need to call a static method by using a custom parameter. This is how you do it:

class Class1
{
 public static function a($x)
{
 echo 'in function a: ' . $x;
}
}

$functionName = 'a';

// won't work
$str = 'Class1::' . $functionName;
$$str('4a');

// this is how you do it
call_user_func(array('Class1', $functionName), '4b'); 

That code should output: in function a: 4b

Please also check call_user_func_array if you need to send the parameters as an array.

Leave a Reply

Your email address will not be published. Required fields are marked *