Array of closures inside a class

It looks like you cannot have an array of callable methods defined within the class. Why not?

Why is this valid PHP (see http://3v4l.org/1JeQr )

$methods = array(
    1 => function($subject, $value){
        return ($subject == $value);
    }
);

var_dump($methods[1]('a', 'a'));

But not that (see http://3v4l.org/FL449 )

class Foo {
    public static $methods = array(
        1 => function($subject, $value){
            return ($subject == $value);
        }
    );
}

var_dump(Foo::$methods[1]('a', 'a'));
+4
source share
2 answers

A very quick answer, since I work from a mobile phone (it may eventually be edited later.

The closure definition is actually performed by an instance of the type object Closure. PHP only supports internal internal types as the default values ​​for your classes, which means that building a closure will obviously not work.

+5
source

, , . . , , , , , .

, . :

class Foo {
    public static $methods;

    function __construct() {
        $this->methods = array(
                               1 => function($subject, $value) {
                                       return ($subject == $value);
                                    }
                               );
    }
}
-1

All Articles