Kav*_*gel 9 php anonymous-function
只是想知道为什么这样的东西不起作用:
public function address($name){
    if(!isset($this->addresses[$name])){
        $address = new stdClass();
        $address->city = function($class = '', $style = ''){
            return $class;
        };          
        $this->addresses[$name] = $address;
    }
    return $this->addresses[$name];
}
Run Code Online (Sandbox Code Playgroud)
把它称为echo $class->address('name')->city('Class')应该回应Class,但是我得到了Fatal error: Call to undefined method stdClass::city()
我可以找到一个更好的方法来做到这一点,因为这会变得混乱,但我想知道我在那里做错了什么,或者PHP不支持这个以及为什么.
PHP在调用致命错误时是正确的,Call to undefined method stdClass::city()因为对象$class->address('name') 没有方法 city.Intead,这个对象的属性 city是Closure Class的实例(http://www.php.net/manual/en/class.closure.php)你可以验证这个:var_dump($class->address('name')->city)
我发现调用这个匿名函数的方法是:
$closure = $class->address('name')->city;
$closure('class');
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助!
小智 5
遗憾的是,它在 stdClass 中是不可能的,但有一个解决方法 - PHP Anonymous Object。
// define by passing in constructor
$anonim_obj = new AnObj(array(
    "foo" => function() { echo "foo"; }, 
    "bar" => function($bar) { echo $bar; } 
));
$anonim_obj->foo(); // prints "foo"
$anonim_obj->bar("hello, world"); // prints "hello, world"
Run Code Online (Sandbox Code Playgroud)