array ( 0 => 'index.php', 1 => 'PHP Manual', ), 'head' => array ( 0 => 'UTF-8', 1 => 'en', ), 'this' => array ( 0 => 'closure.bindto.php', 1 => 'Closure::bindTo', 2 => 'Duplicates the closure with a new bound object and class scope', ), 'up' => array ( 0 => 'class.closure.php', 1 => 'Closure', ), 'prev' => array ( 0 => 'closure.bind.php', 1 => 'Closure::bind', ), 'next' => array ( 0 => 'closure.call.php', 1 => 'Closure::call', ), 'alternatives' => array ( ), 'source' => array ( 'lang' => 'en', 'path' => 'language/predefined/closure/bindto.xml', ), 'history' => array ( ), ); $setup["toc"] = $TOC; $setup["toc_deprecated"] = $TOC_DEPRECATED; $setup["parents"] = $PARENTS; manual_setup($setup); contributors($setup); ?>
(PHP 5 >= 5.4.0, PHP 7, PHP 8)
Closure::bindTo — Duplicates the closure with a new bound object and class scope
$newThis, object|string|null $newScope = "static"): ?ClosureCreate and return a new anonymous function with the same body and bound variables as this one, but possibly with a different bound object and a new class scope.
The “bound object” determines the value $this will
have in the function body and the “class scope” represents a class
which determines which private and protected members the anonymous
function will be able to access. Namely, the members that will be
visible are the same as if the anonymous function were a method of
the class given as value of the newScope
parameter.
Static closures cannot have any bound object (the value of the parameter
newThis should be null), but this method can
nevertheless be used to change their class scope.
This method will ensure that for a non-static closure, having a bound
instance will imply being scoped and vice-versa. To this end,
non-static closures that are given a scope but a null instance are made
static and non-static non-scoped closures that are given a non-null
instance are scoped to an unspecified class.
Note: If you only want to duplicate the anonymous functions, you can use cloning instead.
newThisnull for the closure to be unbound.
newScopeExample #1 Closure::bindTo() example
<?php
class A
{
private $val;
public function __construct($val)
{
$this->val = $val;
}
public 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";
?>The above example will output something similar to:
1 2