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.
Binding closures to objects in 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.
name property.<?php $closure = function() { return $this->name; }; $obj = new stdClass(); $obj->name = "Alice"; $boundClosure = $closure->bindTo($obj, $obj); echo $boundClosure();
<?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();
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 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();
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.
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.