如何将变量绑定到Closure?

jas*_*sir 8 php

我正在寻找如何实现一个函数,将任何变量绑定到函数.

使用假设函数\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魔法怎么样?

Chr*_*rdt 4

也许我不明白,但我尝试回答。

正如我从文档中看到的,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)

  • 感谢您的回复,但我已经寻找了一种如何绑定任何变量的方法,而不仅仅是 $this。例如。function (myfunc) use ($a, $b) {...} - $a 和 $b 由 php 的语法功能绑定,我正在寻找一种如何以编程方式执行此操作的方法 (2认同)