我试图玩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类).
原文链接:https://www.f2er.com/php/139512.html这有两种方法.首先,添加__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