What is Closure::bind() in PHP

Viewed 3549

The PHP manual offers little explanation about Closure::bind() and the example was confusing too.

Here's the code example on the site:

class A {
private static $sfoo = 1;
private $ifoo = 2;
}
$cl1 = static function() {
return A::$sfoo;
};
$cl2 = function() {
return $this->ifoo;
};

$bcl1 = Closure::bind($cl1, null, 'A');
$bcl2 = Closure::bind($cl2, new A(), 'A');
echo $bcl1(), "\n";
echo $bcl2(), "\n";

What are the parameters for Closure::bind()?

Null was used in the above, and even the "new" keyword was used too, which makes this even more confusing to me.

2 Answers

If you prefer to use static version, just try to

$cl4 = Closure::bind(function () { return $this->ifoo; }, new A(), 'A');
echo $cl4();
// it returns "2"

It is pretty cool, if you wanna update the property of an object, but there is no 'setter' for the property. For example:

class Product {
  private $name;
  private $local;
  public function __construct(string $name) {
    $this->name = $name;
    $this->local = 'usa':
  }
}
$product1 = new Product('nice product');
echo $product1->local;
// it returns 'usa'

$product2 = \Closure::bind(function () {
  $this->local = 'germany';
  return $this;
}, new Product('nice product'), 'Product');
echo $product2->local;
// it returns 'germany'
Related