1

I want to store anonymous functions in an array inside a class. Below is my working codes. But I don't understand why I must pass in values in the second argument while I have already declare it to be an empty array by default if nothing is set from outside.

-- public function methods($method = "init",$options = array()){--

Any ideas?

class myclass {

    public function __construct() {}

    public function methods($method = "init",$options = array()){

        $methods = array(
            "init" => function($options){
                return $options;
            },

            "run" => function($options){
                return $options;
            },
        );

        return call_user_func_array( $methods[$method], $options);
    }
}

$obj = new myclass();
var_dump($obj->methods("init",array("hello world!"))); // string 'hello world!' (length=12) --> correct.
var_dump($obj->methods("init",array())); // Warning: Missing argument 1 for myclass::{closure}() in...refer to -> "init" => function($options){
var_dump($obj->methods("init")); // Warning: Missing argument 1 for myclass::{closure}() in...refer to -> "init" => function($options){

I thought it should return these as results,

var_dump($obj->methods("init",array())); // array (size=0)  empty
var_dump($obj->methods("init")); //  array (size=0)  empty

1 Answer 1

4

The correct closure declaration for your case is:

$methods = array(
    "init" => function() use ($options){
        return $options;
    },

    "run" => function() use ($options){
        return $options;
    },
);

If you including the $options variables in your closure declaration, its scope will be the closure itself. Therefore, there will be a new $options variable created and overriding the $options variables in the outer function.

By using the use keyword, you tell PHP that you want to use the passed $options variable (which is currently initiated).

Now, you can omit the second parameter in the call_user_func_array call as follows

call_user_func_array($methods[$method])
Sign up to request clarification or add additional context in comments.

1 Comment

then change to call_user_func

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.