2013-02-13 27 views
2

有人能告訴我,保持相同的抽象層次,如何正確地做到這一點?我有這兩個基本的課程,這不符合我的要求。最終resualt應該是:html不打印出我期望它在網頁源中的方式

<div class="test"> 
    content 
</div> 

如果我這樣做是這樣:

class Wrapper{ 

    protected $_html = ''; 

    public function open(){ 
     $this->_html .= '<div class="test">'; 
    } 

    public function close(){ 
     $this->_html .= '</div>'; 
    } 

    public function __toString(){ 
     return $this->_html; 
    } 
} 

class Content{ 

    protected $hmtl .= ''; 

    public function content(){ 
     $wrapper = new Wrapper(); 
     $wrapper->open(); 
     $this->html .= 'test'; 
     $wrapper->close(); 
    } 

    public function __toString(){ 
     return $this->_html; 
    } 
} 

$內容=新內容(); echo $ content-> content();

我拿到了,是的,這是從源頭:

"content"; 

如果我這樣做是這樣:

class Wrapper{ 

    protected $_html = ''; 

    public function open(){ 
     echo $this->_html .= '<div class="test">'; 
    } 

    public function close(){ 
     echo $this->_html .= '</div>'; 
    } 

    // Technically don't need this 
    public function __toString(){ 
     return $this->_html; 
    } 
} 

我拿到了,是的,這是從源頭抓起,

<div class="test"></div> 
"content" 

那麼我做錯了什麼?以及如何保持相同的抽象級別並獲得期望的輸出?

+0

保護$ HMTL <做到這一點 - 你有一個錯字。它應該是$ html – 2013-02-13 20:56:40

回答

1

你想要某種方法添加內容到包裝類如

public function addContent($content){ 
     $this->_html .= $content; 
    } 

,您可以通過

$wrapper = new Wrapper(); 
$content = new Content(); 
$wrapper->open(); 
$wrapper->addContent((string)$content); 
$Wrapper->Close(); 
0

你永遠不會調用Wrapper__toString方法,它會產生HTML標記。我認爲你真正想要的是$this->_html = (string)$wrapper->open()這樣的東西出現。

編輯

其實,你設置的整個邏輯我摸不透。爲什麼你不是從 - > open()和 - > close()方法改爲return