Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

cameronasmith's avatar

Help with Closures

I understand the idea of anonymous functions, but i'm having a little difficulty with the bind and bindTo methods. Please can someone explain the following:

When I use the bindTo method for example:

class myClass {
    public $value = 100;

    public function hello() {
        $this->value++;
        return $this->value;
    }
}


$testBind = $test->bindTo($myClass);

I am getting the idea that within my anonymous function I can access anything that is public from the class (methods, variables), but nothing protected, and private. Is this correct?

For the Closure ::bind i'm having difficulty understanding it.

For example:

<?php
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');
echo $bcl1(), "\n";

$bcl2 = Closure::bind($cl2, new A(), 'A');
echo $bcl2(), "\n";
?>

I understand that on i'm binding to the class A, but what is the third parameter used for and why do a state it sometimes.

I have read the PHP manual but still non the wiser. Does anybody have a more clear explanation on this?

Thanks

0 likes
0 replies

Please or to participate in this conversation.