Home » Php » php – How to bind variables to Closure?

php – How to bind variables to Closure?

Posted by: admin July 12, 2020 Leave a comment


I am looking how to implement a function, that binds any variable to function.

Using hypothetical function \Closure::bindVariable($closure, $name, $value), implementation could be like this:

function bindAnything($closure, $anyVariables)
     foreach ($variables as $variable => $value) {
         \Closure::bindVariable($closure, $variable, $value);
     return $variable;

Unfortunatelly, there is no \Closure::bindVaraiable. There is \Closure::bind, but only $this is bound by this function.


UPDATE: It seems there is no way how to easily do this. What about some generating code & eval magic?

How to&Answers:

Maybe I do not understand, but I try to answer.

As I can see from the documentation, the bind method is here, to set an object context for the closure.

So if you have object foo:

class foo {};
$foo = new foo();

You can access to foo by $this in the closure.

Maybe you want to have something like that:

$foo = new stdClass();
$foo->bar = "42";

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

echo $closure();

Maybe you want this:

function bindAnything($closure, $anyVariables)
    $obj = (object)$anyVariables;
    return $closure;

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

var $arr = ["foo" => "bar"];

$newClosure = bindAnything($closure, $arr);
echo $newClosure();