0

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?

4 Answers 4

2
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

Sign up to request clarification or add additional context in comments.
2

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);

Comments

1

call_user_func_array

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

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])
);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.