Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Bind

A closure, when build on a method, is bound to an object. When the closure is executed, it will be with that object. Unless the closure is rebound with another object: in that case, the new object will be used as context for the closure execution.

<?php

class Elephpant {
        public function __construct(private int $age) {    }

    public function trumpet() {  echo $this->age;  }
}

$fn = Closure::fromCallable([new Elephpant(10), 'trumpet']);
$fn();

$fn2 = $fn->bindTo(new Elephpant(99), Elephpant::class);
$fn2();

// $fn is called with another object
$fn->call(new Elephpant (100));

?>

Documentation

See Also