繁体   English   中英

小胡子(php)和对象?

[英]Mustache (php) and objects?

给出以下示例,是否有人可以推荐从模板访问$ string或HelloWorld :: getString()而不扩展Mustache类的最佳实践?

<?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,它会按预期工作。 我错过了什么?

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

{{getString}}

您可能想看一下PHP的magic __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 //
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM