PHP 7.0.6 Released

Closure::bindTo

(PHP 5 >= 5.4.0, PHP 7)

Closure::bindTo Duplicates the closure with a new bound object and class scope

Description

public Closure Closure::bindTo ( object $newthis [, mixed $newscope = "static" ] )

Create 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 function can nevertheless be used to change their class scope.

This function 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.

Parameters

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 the object will be used instead. This determines the visibility of protected and private methods of the bound object.

Return Values

Returns the newly created Closure object or FALSE on failure

Examples

Example #1 Closure::bindTo() example

<?php

class {
    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";
?>

The above example will output something similar to:

1
2

See Also

User Contributed Notes

Nezar Fadle
1 year ago
We can use the concept of bindTo to write a very small Template Engine:

#############
index.php
############

<?php

class Article{
    private
$title = "This is an article";
}

class
Post{
    private
$title = "This is a post";
}

class
Template{

    function
render($context, $tpl){

       
$closure = function($tpl){
           
ob_start();
            include
$tpl;
            return
ob_end_flush();
        };

       
$closure = $closure->bindTo($context, $context);
       
$closure($tpl);

    }

}

$art = new Article();
$post = new Post();
$template = new Template();

$template->render($art, 'tpl.php');
$template->render($post, 'tpl.php');
?>

#############
tpl.php
############
<h1><?php echo $this->title;?></h1>
tatarynowicz at gmail dot com
3 years ago
You can do pretty Javascript-like things with objects using closure binding:

<?php
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();

?>
safakozpinar at gmail dot com
4 years ago
Private/protected members are accessible if you set the "newscope" argument (as the manual says).

<?php
$fn
= function(){
    return ++
$this->foo; // increase the value
};

class
Bar{
    private
$foo = 1; // initial value
}

$bar = new Bar();

$fn1 = $fn->bindTo($bar, 'Bar'); // specify class name
$fn2 = $fn->bindTo($bar$bar); // or object

echo $fn1(); // 2
echo $fn2(); // 3
amica at php-resource dot de
4 years ago
With rebindable $this at hand it's possible to do evil stuff:

<?php
   
class A {
        private
$a = 12;
        private function
getA () {
            return
$this->a;
        }
    }
    class
B {
        private
$b = 34;
        private function
getB () {
            return
$this->b;
        }
    }
   
$a = new A();
   
$b = new B();
   
$c = function () {
        if (
property_exists($this, "a") && method_exists($this, "getA")) {
           
$this->a++;
            return
$this->getA();
        }
        if (
property_exists($this, "b") && method_exists($this, "getB")) {
           
$this->b++;
            return
$this->getB();
        }
    };
   
$ca = $c->bindTo($a, $a);
   
$cb = $c->bindTo($b, $b);
    echo
$ca(), "\n"; // => 13
   
echo $cb(), "\n"; // => 35
?>
anthony bishopric
4 years ago
Closures can rebind their $this variable, but private/protected methods and functions of $this are not accessible to the closures.

<?php
$fn
= function(){
    return
$this->foo;
};

class
Bar{
    private
$foo = 3;
}

$bar = new Bar();

$fn = $fn->bindTo($bar);

echo
$fn(); // Fatal error: Cannot access private property Bar::$foo
To Top