__toString does not output



我发现条目 PHP OOP - toString 不起作用,但它没有解决我的问题,因为我相信我正确地调用了神奇的方法......

这是我的代码:

class Alerts {
    public $message;
    public $type;
    public $output;
    public function __construct($message_id)
    {
    include 'con.php';          
    $stmt = $conn->prepare(
    'SELECT * FROM alerts WHERE id = :message_id');
    $stmt->execute(array(':message_id' => $message_id));
    while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
        $this->type = $row['type'];
        $this->message = $row['message'];  
    }
    }
    public function __toString (){
        $output ='';
        $output .= "<div class='" . $this->type . "'><button class='close' data-dismiss='alert'></button>";
        $output .= "<i class='fa fa-check-circle'></i>&nbsp;<strong>";
        $output .= $this->message;
        $output .= "</strong> </div>";
        return $output;
     } 
}

如果我调用以下内容,它就会起作用:

$message_id = 6;
$alert = new Alerts($message_id);
$output ='';
$output .= "<div class='" . $alert->type . "'><button class='close' data-dismiss='alert'></button>";
$output .= "<i class='fa fa-check-circle'></i>&nbsp;<strong>";
$output .= $alert->message;

$output .= "</strong> </div>";

在页面上,但如果我使用,则不会:

$message_id = 6;
$alert = new Alerts($message_id);
echo $alert->output;

我是 PHP OOP 的新手,非常感谢您的帮助

来自 PHP 文档:

__toString() 方法允许类决定当它被视为字符串时它将如何反应。例如,echo $obj;将打印的内容。此方法必须返回一个字符串,否则会发出致命的E_RECOVERABLE_ERROR级错误。

按照这种逻辑,执行echo $alert->output;将只输出在类中声明的空白属性public $output;public $output为空且未被修改的两个原因是:

  1. 您不会在 __toString() 方法的上下文中访问$this->output
  2. 当您访问对象的任何方法或属性时,不会调用__toString()当您将对象视为字符串时。

如果您决定使用__toString(),您实际上应该做的是:

echo $alert;

最新更新