在新的 stdClass 中声明一个匿名函数 [英] Declaring an anonymous function within new stdClass

查看:24
本文介绍了在新的 stdClass 中声明一个匿名函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只是想知道为什么这样的事情不起作用:

Just wondering why something like this doesn't work:

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];
}

echo $class->address('name')->city('Class') 一样调用它应该只是 echo Class,但是我得到 <代码>致命错误:调用未定义的方法 stdClass::city()

Calling it like echo $class->address('name')->city('Class') should just echo Class, however I get Fatal error: Call to undefined method stdClass::city()

我可以找到更好的方法来做到这一点,因为这会变得混乱,但我想知道我在那里可能做错了什么,或者 PHP 是否不支持这一点以及为什么.

I can find a better way to do this, because this will get messy, but I'm wondering what I might be doing wrong there, or if PHP doesn't support this and why.

推荐答案

PHP 在调用致命错误时是正确的 Call to undefined method stdClass::city() 因为对象 $class->address('name') 没有方法 city.相反,这个对象具有属性 city,它是闭包类的实例(http://www.php.net/manual/en/class.closure.php)您可以验证这一点:var_dump($class->address('name')->city)

PHP is right when invoke fatal error Call to undefined method stdClass::city() because object $class->address('name') has no method city. Intead, this object has property city which is instance of Closure Class (http://www.php.net/manual/en/class.closure.php) You can verify this: var_dump($class->address('name')->city)

我发现调用这个匿名函数的方法是:

I found the way to call this anonymous function is:

$closure = $class->address('name')->city;
$closure('class');

希望这会有所帮助!

这篇关于在新的 stdClass 中声明一个匿名函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆