Zend Framework:通过引用传递视图助手不起作用
这是一个简单的视图助手(注意传递引用参数):
class Zend_View_Helper_MyViewHelper extends Zend_View_Helper_Abstract
{
public function MyViewHelper(&$array)
{
unset($array['someExistingKey']);
}
}
这在视图中不起作用。 $array['someExistingKey']
仍然设置(除了在方法的直接上下文中)。 Zend 必须采取一些措施来防止数组通过引用传入。关于解决方案有什么想法吗?
Here is a simple view helper (notice the pass-by-reference argument):
class Zend_View_Helper_MyViewHelper extends Zend_View_Helper_Abstract
{
public function MyViewHelper(&$array)
{
unset($array['someExistingKey']);
}
}
This does not work in the view. $array['someExistingKey']
is still set (except within the immediate context of the method). Zend must be doing something to prevent the array from being passed in by reference. Any ideas on a solution?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当您从模板中调用
$this->MyViewHelper($array)
时,您实际上并没有直接调用帮助器类,Zend_View 正在实例化该类并为您调用它。所以我认为你可能很难让这个工作正常进行。您最好的选择可能是使用 Zend_Registry,或重构以采取不需要全局的不同方法。When you call
$this->MyViewHelper($array)
from your templates you are not actually calling the helper class directly, Zend_View is instantiating the class and calling it for you. So I think you might have trouble getting this working. Your best bet is probably to use Zend_Registry, or refactor to take a different approach not requiring a global.我只是想到了一个解决方法。您只需手动调用帮助程序,而不是让 ZF 通过 call_user_func_array 来调用它。
Ref.php
如您所见,您可以跳过必须将主方法命名为文件名的约定,但我仍然推荐它。
现在,您可以在视图/控制器中传递引用:
基本上,这就是
$this->ref()
所做的:获取帮助器,然后调用call_user_func_array
。有些人可能会在使用
$this->getHelper('Ref')->ref()
而不是$this->ref()
时遇到问题,但是有用。I just thought of a workaround. You just have to call the helper manually, instead of letting ZF call it through
call_user_func_array
.Ref.php
As you can see, you can skip the convention of having to name your main method as the filename, but I still recommend it.
Now, you can pass references in views/controllers:
Basically, this is what
$this->ref()
does: gets the helper, then callscall_user_func_array
.Some people may have problems using
$this->getHelper('Ref')->ref()
instead of$this->ref()
though, but it works.