Php __toString不输出
我发现PHP OOP-toString条目不起作用,但它没有解决我的问题,因为我相信我正确地调用了magic方法 这是我的密码:Php __toString不输出,php,oop,tostring,Php,Oop,Tostring,我发现PHP OOP-toString条目不起作用,但它没有解决我的问题,因为我相信我正确地调用了magic方法 这是我的密码: class Alerts { public $message; public $type; public $output; public function __construct($message_id) { include 'con.php'; $stmt = $conn->pre
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> <strong>";
$output .= $this->message;
$output .= "</strong> </div>";
return $output;
}
}
我是PHP OOP的新手,非常感谢您的帮助:
\uuuToString()
方法允许类决定当它被视为字符串时将如何反应。例如,echo$obj代码>将打印。此方法必须返回一个字符串,否则将发出致命的E\u可恢复\u错误
级别错误
按照这种逻辑,执行echo$alert->output代码>将只输出空白属性<代码>公共$输出;<在类中声明的代码>。public$output
为空且未被修改的两个原因是:
在\uu toString()
方法的上下文中,不能访问$this->output
\uuuu toString()
只有在将对象视为字符串时,才会在访问对象的任何方法或属性时被调用
如果您决定使用\uu toString()
,您实际上应该做的是:
echo $alert;
当在字符串上下文中使用对象时,将自动调用\uuu toString()
方法。只需执行echo$alert代码>不确定您为什么认为需要->输出
。。。我所知道的任何语言都没有使用它来调用toString
。也不要忘记,如果您试图实际修改公共属性$output
,则必须在方法上下文中使用$this->output
。您好,谢谢你的回复,我按照你的建议做了,并使用echo$alert打印出来,但我在以下情况下得到错误:可捕获致命错误:方法警报::_toString()必须在/var/www/vhosts/dev-roe-vti.org/httpdocs/mdashboard/login.php中在线返回字符串值130@janetspagnol不客气。如果我的解决方案对您有所帮助,可以通过单击我的答案左侧向上/向下箭头下方的灰色复选标记将该解决方案标记为已接受,使其变为绿色。这里是var#u dump,如果它有助于对象(警报)#3(2){[“message”]=>string(78)“很抱歉,我们没有与这些凭证匹配的高级导师”[“type”]=>string(18)“alert-alert-danger”}@janetspagnol您是否修改了\u-toString()
方法?正如错误所说,您必须返回字符串以外的内容。无论如何,这都应该在一个新问题中解决,因为它与这个问题无关。@janetspagnolvar\u dump
一点帮助都没有。您的\uuu toString()
方法中有什么?
$message_id = 6;
$alert = new Alerts($message_id);
echo $alert->output;
echo $alert;