2011-09-15 13 views
1

Mustacheクラスを拡張せずにテンプレートから$ stringまたはHelloWorld :: getString()にアクセスするためのベストプラクティスをお勧めしますか?口ひげ(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

これは本当に "私は何が足りないですか"という質問に答えるのに役立ちました。ありがとうございました。問題は、Mustacheを使って作業している間に解決策ではないように見えることです。 – Mike

3

これは恥ずかしいです:

はこのようにそれを試してみてください。解決策は簡単です:

{{getString}} 
+0

笑。私はしばらく笑わなかった。 –

関連する問題