CodeBlanks Logo Icon CodeBlanks

Closure binding (bindTo)

PHP course · Expert · Lesson 13/54

Learn to bind a closure to a different object with bindTo().

Binding $this with bindTo

A closure cannot use $this in the context where it was defined. But with bindTo($newThis) it binds to a different object; $this now points to that object.

For example $cb = function () { return $this->name; }; cannot be called on its own. $cb->bindTo($obj) returns a new closure where $this is $obj.

This is a powerful way to reuse closures across classes; it acts like a fake method.

The Closure::bind static method

Closure::bind($cb, $newThis, $scope) is a static method. It does the same job as bindTo but does not touch the original closure; it returns a new one.

The third parameter $scope decides from which class visibility scope $this is seen. To access private fields you pass the class name.

Which one to pick is a matter of style: bindTo is object-oriented, Closure::bind is a static call.

Exercise Bind a closure to a stdClass

Define a closure named $greet: function () { return 'Hello ' . $this->name; }. Create an object with $obj = new stdClass; and assign $obj->name = 'Alex';. Bind the closure to $bound with bindTo($obj). Print the result with echo $bound() . "\n";.

Show example solution
Write $greet = function () { return 'Hello ' . $this->name; };. Set $obj = new stdClass; $obj->name = 'Alex';. Bind with $bound = $greet->bindTo($obj);. Write echo $bound() . "\n";.
Example solution:
<?php
// Bind the closure to a stdClass object with bindTo
$greet = function () {
    return 'Hello ' . $this->name;
};
$obj = new stdClass;
$obj->name = 'Alex';
$bound = $greet->bindTo($obj);
echo $bound() . "\n";

Test yourself

  1. Complete the bindTo call

    <?php
    $greet = function () { return $this->name; };
    $obj = new stdClass;
    $obj->name = 'Alex';
    $bound = $greet->____($obj);
    echo $bound() . "\n";
    
    Show answer
    <?php
    $greet = function () { return $this->name; };
    $obj = new stdClass;
    $obj->name = 'Alex';
    $bound = $greet->bindTo($obj);
    echo $bound() . "\n";
    
  2. Match the binding concepts

    bindTo()
    Instance method
    Closure::bind()
    Static method
    $this
    Bound object
    scope
    Visibility scope
  3. What does bindTo do?

    • Binds the closure to a new $this
    • Deletes the closure
    • Turns the closure into an array
    • Converts the closure to text
    Show answer

    Binds the closure to a new $this — Correct. bindTo($obj) binds the closure to a new object; $this becomes $obj.

All lessons in Expert