我正在寻找如何实现一个函数,将任何变量绑定到函数.
使用假设函数\Closure::bindVariable($closure, $name, $value),实现可能是这样的:
function bindAnything($closure, $anyVariables)
{
foreach ($variables as $variable => $value) {
\Closure::bindVariable($closure, $variable, $value);
}
return $variable;
}
Run Code Online (Sandbox Code Playgroud)
不幸的是,没有\Closure::bindVaraiable.有\Closure::bind,但只$this受此功能的约束.
http://php.net/manual/en/class.closure.php
更新:似乎没有办法轻松做到这一点.那些生成代码和eval魔法怎么样?
也许我不明白,但我尝试回答。
正如我从文档中看到的,bind 方法在这里,用于为闭包设置对象上下文。
所以如果你有对象 foo:
class foo {};
$foo = new foo();
Run Code Online (Sandbox Code Playgroud)
foo您可以通过$this闭包访问。
也许你想要这样的东西:
$foo = new stdClass();
$foo->bar = "42";
$closure = function() {
return $this->bar;
};
$closure.bindTo($foo);
echo $closure();
Run Code Online (Sandbox Code Playgroud)
也许你想要这个:
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();
Run Code Online (Sandbox Code Playgroud)