【发布时间】:2011-05-03 00:08:01
【问题描述】:
我最近一直在问一些关于这个主题的问题,所以我觉得将相关问题联系起来是合适的。
PHP closures and implicit global variable scope
我有一组使用闭包的类,如下例所示(请记住,我为此线程快速拼凑了这个示例)我的问题涉及将 $obj 参数传递给函数。
是否存在任何类型的 magic 变量 (cough-$this-cough) 可以让我访问调用它的对象,而不是需要声明一个占位符参数$obj 或其他什么?也许我读错了,但似乎我正在寻找的功能已被删除,至少在 $this 的上下文中。
class Test{
private $_color;
protected $_children = array();
public function __construct(Closure $function){
$function($this);
}
public function create(Closure $function){
return new self($function);
}
public function color($color){
$this->_color = $color;
return $this;
}
public function add(Closure $function){
$this->_children[] = new Test($function);
return $this;
}
}
Test::create(function($obj){
$obj->color('Red')
->add(function(){
$obj->color('Green');
})
->color('Blue');
});
我能看到的唯一替代方法是在创建时存储每个对象的实例,并提供一个函数来返回该实例,如下所示:
class Test{
private $_color;
private static $_instance;
protected $_children = array();
public function __construct(Closure $function){
self::$_instance = $this;
$function();
}
.
.
.
public static function this(){
return self::$_instance;
}
}
Test::create(function(){
Test::this()
->color('Red')
->add(function(){
Test::this()
->color('Green');
})
->color('Blue');
});
【问题讨论】:
标签: php object scope closures anonymous-function