我似乎对上面提到的方法有问题:
public function __toString()
{
?>
Some html code
Some more html code
<?=echo $this->content?>
Last of the html code
<?
return '';
}
我需要它,在这个方法中,我可以打破PHP代码,这样我就可以更好地格式化和查看HTML代码。但如果我省略了返回,我会得到一个异常:
__toString()必须返回一个字符串值。
我有什么办法可以不用退货?
您可以使用输出缓冲区执行以下操作:
public function __toString()
{
ob_start() ;
?>
Some html code
Some more html code
<?=echo $this->content?>
Last of the html code
<?php
$content = ob_get_content() ;
ob_end_clean() ;
return $content ;
}
因此,实际上,您将输出存储在缓冲区中,将内容放入变量中,清理缓冲区。
之后,您可以成功地返回字符串并使您的函数工作。
你不能绕过return
,它是magic method
,你必须实现它。
虽然其他答案在技术上可能有效,但它们都是对__toString()方法的滥用,该方法用于返回对象的字符串表示。
听起来你需要一种新方法,如
public function outputHTML()
{
?>
Some html code
Some more html code
<?=echo $this->content?>
Last of the html code
<?
}
然后您只需在适当的时候调用$object->outputHTML()
,而不仅仅是调用$object
这更容易理解,并将使将来维护代码变得更简单,因为没有人会期望__toString()
打印出大量标记、文本,然后不返回任何内容。
可能会使用heredoc语法。
public function __toString() {
$contents = <<<EOT
<p>This is some text and you can still use $variables</p>
EOT;
return $contents;
}