Lee Davis
Lee Davis

Reputation: 4756

Array of closures within a class

It appears you can't have an array of callable methods defined within the scope of a 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 this (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'));

Upvotes: 4

Views: 128

Answers (2)

Ocramius
Ocramius

Reputation: 25441

A very quick answer since I am working from mobile phone (can eventually edit later.

Defining a closure actually performs an instantiation of an object of type Closure. PHP only supports native internal types as default values for your classes, which means that constructing a closure obviously won't work.

Upvotes: 5

silkfire
silkfire

Reputation: 26003

This is because the property definitions in a class only allow you to assign simple, direct values. Class constant assigning is further more restrictive. This means that no values derived from a function, no arrays that are filled with derived values or objects, or any arithmetic are allowed in the property definition scope.

If you want to assign an array of closures upon the initialization of the object, you can freely do so in the construct of the class. Like this:

class Foo {
    public static $methods;

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

Upvotes: -1

Related Questions