Php 从类成员返回引用?

Php 从类成员返回引用?,php,smarty,Php,Smarty,我有一个类基本上是这样的: class App { public function newTemplate($filename, $vars=array()) { $smarty = new Smarty; $smarty->compile_dir = $this->template_compile_path; if(count($vars) > 0) { foreach($

我有一个类基本上是这样的:

class App {
    public function newTemplate($filename, $vars=array())
    {
        $smarty = new Smarty;
        $smarty->compile_dir = $this->template_compile_path;
        if(count($vars) > 0)
        {
            foreach($vars as $v_key => $v_name)
            {
                $smarty->assign($v_key, $v_name);
            }
        }
        return $smarty;
    }
}
但是,当我创建“App”实例时,对$smarty的引用似乎被破坏了,因为对membermethods的每次调用似乎都不起任何作用:

$app = new App;
$tpl = $app->newTemplate("index.tmpl");
$tpl->assign("foo", "bar"); // {$foo} does not appear with "bar" in the template
现在我想知道为什么?当然,我试着使用参考文献:

...
public function &newTemplate()
...
。。。但这不起作用。变量引用似乎也不起作用:

...
$tpl = &$app->newTemplate("index.tmpl");
...

是什么导致这里的PHP没有返回正确的引用?非常感谢您的帮助

您正在使用$this->template\u compile\u路径;初始化Smarty。你初始化这个了吗?另一方面,您是否将PHP设置为显示错误?您是否查看了web服务器错误日志


如果您对函数返回的内容有疑问,请对结果使用print\r。

解决方案似乎并不简单,因为调用Smarty::display()后Smarty不允许更改变量,这会导致对Smarty::assign()的每次调用都丢失

因此,我创建了一个重载类,该类继承Smarty,并让它完成肮脏的工作

作为结论:

  • 如果您仍然需要在模板中分配变量,请不要调用Smarty::display()
  • 在调用Smarty::display()之前调用Smarty::assign()

我自己也觉得这种行为有点奇怪,但不管怎样,我想P

Yes,$this->template\u compile\u路径在类中定义。在玩了一会儿之后,我发现了一个实际的问题(我将把它作为答案发布在一个不相关的注释上),有一天您可能想尝试使用PHP本身进行模板化。曾经有一段时间,我是一个狂热的Smarty用户,直到我偶然发现PHP框架没有使用第三方模板系统。这些天来,我通过PHP实现了这一点,我不得不说这让我的生活变得更轻松了……我也曾直接使用PHP进行模板制作,但由于缺乏输出操作方法,因此。。凌乱的