2011-09-15 49 views
1

鑑於以下示例,任何人都可以推薦從模板訪問$ string或HelloWorld :: getString()而不擴展Mustache類的最佳做法嗎?小鬍子(php)和對象?

<?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爲public,它就像預期的那樣工作。我錯過了什麼?

回答

1

您可能想看看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 // 
     } 
    } 
} 
+0

這對於回答「我缺少什麼」的問題非常有幫助。謝謝。問題在於,在使用鬍子時,它似乎不是解決方案。 – Mike

3

這是令人尷尬的。解決辦法很簡單:

{{getString}} 
+0

哈哈。我沒有笑一陣子。 –