1

鉴于以下示例,任何人都可以推荐一种最佳做法,即在不扩展 Mustache 类的情况下从模板访问 $string 或 HelloWorld::getString() 吗?

<?php    
Class HelloWorld{
    protected $string;
    function __construct(){
        $this->string = 'Hello World';
    }
    function setString($str) { $this->string = $str; }
    function getString() { return $this->string; }
}

# here goes nothing
$h = new HelloWorld();
$m = new Mustache();
echo $m->render('{{string}}', $h);
?>

正如你想象的那样,如果我公开 $string,它会按预期工作。我错过了什么?

4

2 回答 2

3

这很尴尬。解决方案很简单:

{{getString}}
于 2011-09-17T08:53:22.543 回答
1

您可能想看看 PHP 的魔法 __get__set方法。

试试这样:

Class HelloWorld{
    protected $string;
    function __construct(){
        $this->string = 'Hello World';
    }
    function __set($var, $value) { 
        switch($var){
            case 'string': $this->string = $value; break;
            default: // do nothing //
        }
    }
    function __get($var) { 
        switch($var){
            case 'string': return $this->string;
            default: // do nothing //
        }
    }
}
于 2011-09-15T11:39:15.127 回答