Closure::bindTo
(PHP 5 >= 5.4.0)
Closure::bindTo — Duplicates the closure with a new bound object and class scope
说明
public Closure Closure::bindTo( object $newthis[, mixed $newscope = 'static'] )
Create and return a new anonymousfunction with the same body and bound variables as this one, butpossibly with a different bound object and a new class scope.
The “bound object” determines the value $this willhave in the function body and the “class scope” represents a classwhich determines which private and protected members the anonymousfunction will be able to access. Namely, the members that will bevisible are the same as if the anonymous function were a method ofthe class given as value of the newscopeparameter.
Static closures cannot have any bound object (the value of the parameter newthis should be NULL), but this function cannevertheless be used to change their class scope.
This function will ensure that for a non-static closure, having a boundinstance will imply being scoped and vice-versa. To this end,non-static closures that are given a scope but a NULL instance are madestatic and non-static non-scoped closures that are given a non-nullinstance are scoped to an unspecified class.
Note:
If you only want to duplicate the anonymous functions, you can use cloning instead.
参数
newthis
The object to which the given anonymous function should be bound, or NULL for the closure to be unbound.
newscope
The class scope to which associate the closure is to be associated, or'static' to keep the current one. If an object is given, the type of theobject will be used instead. This determines the visibility of protectedand private methods of the bound object.
返回值
Returns the newly created Closure object 或者在失败时返回 FALSE
范例
Example #1 Closure::bindTo() example
<?php
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";
$cl = $cl->bindTo($ob2);
echo $cl(), "\n";
?>
以上例程的输出类似于:
1
2
参见
◾Anonymous functions
◾ Closure::bind() - Duplicates a closure with a specific bound object and class scope
发表评论 取消回复