1

I have the following PHP code:

function test($callback) {
    $parameter = func_get_args()[0]["parameter"]; 
    var_dump$parameter);
}

test(function($var, $var2) {});

The call generates this error:

Fatal error: Cannot use object of type Closure as array

How I can covert the Closure Object to an Array?

I've tried the following things:

function test($callback) {
    $parameter = func_get_args()[0];
    $parameter = json_decode(json_encode($parameter), true);
    var_dump($parameter);
}

which outputs:

array(0) {}

and:

function test($callback) {
    $parameter = func_get_args()[0];
    $parameter = (array) $parameter;
    var_dump($parameter);
}

which outputs:

array(1) { 
    [0]=> object(Closure)#1 (1) { 
        ["parameter"]=> array(2) { 
             ["$var"]=> string(10) "" 
             ["$var2"]=> string(10) "" 
        } 
    } 
}

What can I do?

1 Answer 1

2

Do you want to get an array with parameters of a callback? If you do, you can use Reflection API.

function test() {
    $callback = func_get_args()[0];
    $rf = new ReflectionFunction($callback);
    $params = array();
    foreach ($rf->getParameters() as $param) {
        $params[] = $param->getName();
    }
    var_dump($params);
}
Sign up to request clarification or add additional context in comments.

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.