开发者

Returning a reference from a Class member?

I've a class that basically looks like this:

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;
    }
}

However, when I create a Instance of 'App', the reference to $smarty seems broken, as every call to the membermethods don't seem to do anything:

$app = new App;
$tpl = $app->newTemplate("index.tmpl");
$tpl->assign("foo", "bar"); // {$foo} does not appear with "bar" in the template

Now I wonder why? Of course I tried to use references:

...
public function &newTemplate()
...

... But that doesn't work. Variable references don't seem to work either:

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

What is causing PHP here not to return a proper reference? Help is very appreciated!


You're using $this->template_compile_path; to initialize Smarty. Have you initialized this? On a different note have you set PHP to display errors? Have you looked in your web server error log?

If you have a doubt about what a function returns use print_r on the result.


The solution doesn't seem very trivial, as Smarty doesn't allow changing variables once Smarty::display() has been called, which causes every call to Smarty::assign() to be lost.

So I created a overloaded class that inherits Smarty, and let it do the dirty job.

as conclusion:

  • never call Smarty::display() if you still have to assign vars in your template.
  • call Smarty::assign() before calling Smarty::display().

I found that behaviour a little strange myself, but whatever, I guess. :P

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜