闭包:在局部作用域(通常是函数或方法)内,引用了外部数据的函数。
Closure Closure::bindTo ( object $newthis
[, mixed $newscope
= 'static' ] )
复制当前闭包对象,绑定指定的$this对象和类作用域。
-
绑定给匿名函数的一个对象,或者
NULL
来取消绑定。 -
关联到匿名函数的类作用域,或者 'static' 保持当前状态。如果是一个对象,则使用这个对象的类型为新的类作用域。 这会决定绑定的对象的 保护、私有成员 方法的可见性。
newthis
newscope
示例1:
class A {
function __construct($val) {
$this->val = $val;
}
function getClosure() {
//returns closure bound to this object and scope
return function() { return $this->val; };
}
}
$ob1 = new A(1);
$ob2 = new A(2);
$cl = $ob1->getClosure();
echo $cl(), "\n"; // 1
$cl = $cl->bindTo($ob2);
echo $cl(), "\n"; // 2
简述:改变 对象的内$this的指向 。由此可见,是不是有点类似javascript 中的 call,apply,bind的味道。
题外,用go接口实现 的中receiver 接收器 参数 说法来更为贴切。
php对象类js (Javascript-like)
事实上也的确可以这样操作了,只需要使用以下trait
trait DynamicDefinition {
public function __call($name, $args) {
if (is_callable($this->$name)) {
return call_user_func($this->$name, $args);
}
else {
throw new \RuntimeException("Method {$name} does not exist");
}
}
public function __set($name, $value) {
$this->$name = is_callable($value)?
$value->bindTo($this, $this):
$value;
}
}
class Foo {
use DynamicDefinition;
private $privateValue = 'I am private';
}
$foo = new Foo;
$foo->bar = function() {
return $this->privateValue;
};
// prints 'I am private'
print $foo->bar();
这样 是不是感觉在写js ?