PHP 手册对Closure::bind()几乎没有解释,而且这个例子也很混乱。
这是网站上的代码示例:
class A {
private static $sfoo = 1;
private $ifoo = 2;
}
$cl1 = static function() {
return A::$sfoo;
};
$cl2 = function() {
return $this->ifoo;
};
$bcl1 = Closure::bind($cl1, null, 'A');
$bcl2 = Closure::bind($cl2, new A(), 'A');
echo $bcl1(), "\n";
echo $bcl2(), "\n";
Run Code Online (Sandbox Code Playgroud)
Closure::bind() 的参数是什么?
上面使用了 Null,甚至还使用了“new”关键字,这让我更加困惑。
If you put the value of $cl2 as a method of class A, the class looks like this:
class A {
public $ifoo = 2;
function cl2()
{
return $this->ifoo;
}
}
Run Code Online (Sandbox Code Playgroud)
and you can use it like this:
$x = new A();
$x->cl2();
# it prints
2
Run Code Online (Sandbox Code Playgroud)
But, because $cl2 is a closure and not a member of class A, the usage code above does not work.
The method Closure::bindTo() allows using the closure as it were a method of class A:
$cl2 = function() {
return $this->ifoo;
};
$x = new A();
$cl3 = $cl2->bindTo($x);
echo $cl3();
# it prints 2
$x->ifoo = 4;
echo $cl3();
# it prints 4 now
Run Code Online (Sandbox Code Playgroud)
The closure uses the value of $this but $this is not defined in $cl2.
When $cl2() runs, $this is NULL and it triggers an error ("PHP Fatal error: Using $this when not in object context").
Closure::bindTo() creates a new closure but it "binds" the value of $this inside this new closure to the object it receives as its first argument.
Inside the code stored in $cl3, $this has the same value as the global variable $x. When $cl3() runs, $this->ifoo is the value of ifoo in object $x.
Closure::bind() is the static version of Closure::bindTo(). It has the same behaviour as Closure::bindTo() but requires an additional argument: the first argument must be the closure to bind.