1

I seem to have a problem with the method mentioned above:

    public function __toString()
    {
        ?>
        Some html code
        Some more html code
        <?=echo $this->content?>
        Last of the html code
        <?
        return '';
    }

I need it that in this method I can break PHP code, so I can better format and see the HTML code. But if I omit the return I get the exception:

__toString() must return a string value.

Any way i can manage without the return?

4

3 回答 3

1

虽然其他答案在技术上可能有效,但它们都是对 __toString() 方法的滥用,该方法用于返回对象的字符串表示形式。

在我看来,您需要一种新方法,例如

public function outputHTML()
{
    ?>
    Some html code
    Some more html code
    <?=echo $this->content?>
    Last of the html code
    <?
}

然后您只需在适当的时候通过调用$object->outputHTML()而不是调用$object

这更容易理解,并且将来维护代码会更简单,因为没有人会真正期望__toString()打印出大量标记、文本然后不返回任何内容。

于 2013-07-03T16:31:29.560 回答
1

您可以使用输出缓冲区执行以下操作:

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,你必须实现它。

于 2013-07-03T16:19:39.803 回答
0

可能是heredoc 语法的用途。

public function __toString() {
    $contents = <<<EOT

    <p>This is some text and you can still use $variables</p>

EOT;

    return $contents;
}
于 2013-07-03T16:21:49.113 回答