Svetoslav
Svetoslav

Reputation: 4686

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?

Upvotes: 0

Views: 123

Answers (4)

mickmackusa
mickmackusa

Reputation: 48031

You were very close to what is valid syntax as of PHP5.4. You merely need to use curly braces and quoting to encapsulate the method name. Demo

Set up:

class USER // should be a StudlyCased class name
{
    static function find_by_username($name)
    {
        printf('You tried to find a user by username "%s"', $name);
    }
}

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

Valid modern calls without call_user_func_array():

  • Interpolation:

    $array[0]::{"find_by_{$array[1]}"}($array[3]);
    
  • Concatenation:

    $array[0]::{'find_by_' . $array[1]}($array[3]);
    

Output: You tried to find a user by username "test"


@Gumbo's correct implementation will work all the way down to PHP5.0. Demo

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

Upvotes: 0

Sascha Galley
Sascha Galley

Reputation: 16091

call_user_func_array

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

Upvotes: 1

Gumbo
Gumbo

Reputation: 655659

You can use call_user_func_array to call a callback with an array as parameters:

$callback = array($array[0], 'find_by_'.$array[1]);
$params = array($array[3]);

$ret = call_user_func_array($callback, $params);

Upvotes: 2

Mark Baker
Mark Baker

Reputation: 212512

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

Upvotes: 2

Related Questions