phpdynamic-programmingstatic-methodsmethod-calldynamic-class

Call a static method using a dynamic class name, method, and parameter


I have a php array with 4 entries. And I need to call a class method using the data in my array.

$array = array('USER', 'username', 'other', 'test');

This I want to use to generate this

$array[0]::find_by_$array[1]($array[3]); 

it must look as

USER::find_by_username(test);

How I can convert the array values into this line?

What is the correct syntax?


Solution

  • call_user_func_array(array($array[0],'find_by_'.$array[1]),$array[3])
    

    But this isn't the cleanest way to manage your code, there's no validation that the class or method exists, so subject to potential failure