2013-02-13 84 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