php – 根据类定义一个闭包作为方法
发布时间:2020-12-13 14:00:34 所属栏目:PHP教程 来源:网络整理
导读:我试图玩php5.3和关闭. 我在这里看到(清单7中的对象关闭:http://www.ibm.com/developerworks/opensource/library/os-php-5.3new2/index.html)可以在回调函数中使用$this,但不是.所以我试图给$$作为使用变量: $self = $this;$foo = function() use($self) {
我试图玩php5.3和关闭.
我在这里看到(清单7中的对象关闭:http://www.ibm.com/developerworks/opensource/library/os-php-5.3new2/index.html)可以在回调函数中使用$this,但不是.所以我试图给$$作为使用变量: $self = $this; $foo = function() use($self) { //do something with $self } 所以要用同样的例子: class Dog { private $_name; protected $_color; public function __construct($name,$color) { $this->_name = $name; $this->_color = $color; } public function greet($greeting) { $self = $this; return function() use ($greeting,$self) { echo "$greeting,I am a {$self->_color} dog named {$self->_name}."; }; } } $dog = new Dog("Rover","red"); $dog->greet("Hello"); Output: Hello,I am a red dog named Rover. 首先这个例子不打印字符串但是返回函数,但这不是我的问题. 其次,我无法访问私有或受保护,因为回调函数是一个全局函数,而不是在上下文中从Dog对象.不是我的问题与以下相同: function greet($greeting,$object) { echo "$greeting,I am a {$self->_color} dog named {$self->_name}."; } 而且我要 : public function greet($greeting) { echo "$greeting,I am a {$self->_color} dog named {$self->_name}."; } 哪个来自狗而不是全球.
嗯,你不能使用$this的全部原因是因为闭包是后台的对象(Closure类).
这有两种方法.首先,添加__invoke方法(如果调用$obj(),调用).. class Dog { public function __invoke($method) { $args = func_get_args(); array_shift($args); //get rid of the method name if (is_callable(array($this,$method))) { return call_user_func_array(array($this,$method),$args); } else { throw new BadMethodCallException('Unknown method: '.$method); } } public function greet($greeting) { $self = $this; return function() use ($greeting,$self) { $self('do_greet',$greeting); }; } protected function do_greet($greeting) { echo "$greeting,I am a {$this->_color} dog named {$this->_name}."; } } 如果您想要修改主机对象时关闭不变,您可以将返回函数更改为: public function greet($greeting) { $self = (clone) $this; return function() use ($greeting,$self) { $self('do_greet',$greeting); }; } 另一个选择是提供一个通用的getter: class Dog { public function __get($name) { return isset($this->$name) ? $this->$name : null; } } 有关更多信息,请参阅:http://www.php.net/manual/en/language.oop5.magic.php (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |