ZF2 中 ViewModel 和 Closure 的奇怪行为
Strange behavior with ViewModel and Closure in ZF2
我尝试将回调函数传递给模板,该函数应该在模板中调用,但回调是在参数传递给方法 setVariable() 后直接调用的
public function testAction() {
$model = new ViewModel();
$callback = function() {
return new \stdClass();
};
$model->setVariable('call', $callback);
\Zend\Debug\Debug::dump([
get_class($callback),
get_class($model->getVariable('call'))
]);
}
结果有点奇怪:
array(2) {
[0] => string(7) "Closure"
[1] => string(8) "stdClass"
}
我不明白为什么会这样。这是错误还是功能?
视图变量存储为自定义 ArrayObject
class Zend\View\Variables
。
在调试中调用 $viewModel->getVariable()
将代理到 offsetGet
方法和 will cause the closure to be invoked.
相关代码。
public function offsetGet($key)
{
// ...
$return = parent::offsetGet($key);
// If we have a closure/functor, invoke it, and return its return value
if (is_object($return) && is_callable($return)) {
$return = call_user_func($return);
}
return $return;
}
如果您想要闭包对象,那么您可能需要考虑使用视图助手。
我尝试将回调函数传递给模板,该函数应该在模板中调用,但回调是在参数传递给方法 setVariable() 后直接调用的
public function testAction() {
$model = new ViewModel();
$callback = function() {
return new \stdClass();
};
$model->setVariable('call', $callback);
\Zend\Debug\Debug::dump([
get_class($callback),
get_class($model->getVariable('call'))
]);
}
结果有点奇怪:
array(2) {
[0] => string(7) "Closure"
[1] => string(8) "stdClass"
}
我不明白为什么会这样。这是错误还是功能?
视图变量存储为自定义 ArrayObject
class Zend\View\Variables
。
在调试中调用 $viewModel->getVariable()
将代理到 offsetGet
方法和 will cause the closure to be invoked.
相关代码。
public function offsetGet($key)
{
// ...
$return = parent::offsetGet($key);
// If we have a closure/functor, invoke it, and return its return value
if (is_object($return) && is_callable($return)) {
$return = call_user_func($return);
}
return $return;
}
如果您想要闭包对象,那么您可能需要考虑使用视图助手。