0
0
PHPprogramming~5 mins

Binding closures to objects in PHP

Choose your learning style9 modes available
Introduction

Binding closures to objects lets you run a small piece of code (closure) as if it belongs to that object. This helps the closure access the object's data easily.

When you want a closure to use or change an object's properties.
When you have a closure outside a class but want it to behave like a method inside an object.
When you want to reuse a closure with different objects without rewriting code.
Syntax
PHP
$closure->bindTo(object|null $newthis, object|string|null $newscope = null): ?Closure

The bindTo method attaches the closure to a new object.

The closure can then access the object's properties and methods as if it was inside the object.

Examples
This example binds a closure to an object so it can access the object's name property.
PHP
<?php
$closure = function() {
    return $this->name;
};

$obj = new stdClass();
$obj->name = "Alice";

$boundClosure = $closure->bindTo($obj, $obj);
echo $boundClosure();
Binding a closure to a class instance with private property access by specifying the class scope.
PHP
<?php
class Person {
    private string $name;
    public function __construct(string $name) {
        $this->name = $name;
    }
}

$closure = function() {
    return $this->name;
};

$person = new Person("Bob");
$boundClosure = $closure->bindTo($person, Person::class);
echo $boundClosure();
Sample Program

This program creates a Car object with a private property model. The closure $getModel is bound to the Car object so it can access the private property and return its value.

PHP
<?php
class Car {
    private string $model;
    public function __construct(string $model) {
        $this->model = $model;
    }
}

$getModel = function() {
    return "Car model is: " . $this->model;
};

$car = new Car("Tesla Model 3");

$boundGetModel = $getModel->bindTo($car, Car::class);
echo $boundGetModel();
OutputSuccess
Important Notes

Binding a closure to an object allows access to private and protected members if the correct scope is given.

Without binding, closures cannot access private or protected properties of objects.

Binding returns a new closure; the original closure remains unchanged.

Summary

Binding closures to objects lets closures access the object's properties and methods.

Use bindTo to attach a closure to an object and optionally specify the class scope.

This technique helps reuse code and access private data safely.