How to bind variables to Closure?

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.

http://php.net/manual/en/class.closure.php


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


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;
};

$closure.bindTo($foo);
echo $closure();

Maybe you want this:

function bindAnything($closure, $anyVariables)
{
    $obj = (object)$anyVariables;
    $closure.bindTo($obj);
    return $closure;
}

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

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

$newClosure = bindAnything($closure, $arr);
echo $newClosure();
链接地址: http://www.djcxy.com/p/87870.html

上一篇: Google Vision条码检测库不在某些设备上安装

下一篇: 如何将变量绑定到Closure?