Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php __toString不输出_Php_Oop_Tostring - Fatal编程技术网

Php __toString不输出

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

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

这是我的密码:

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;
     } 

}
我是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()
    方法?正如错误所说,您必须返回字符串以外的内容。无论如何,这都应该在一个新问题中解决,因为它与这个问题无关。@janetspagnol
    var\u dump
    一点帮助都没有。您的
    \uuu toString()
    方法中有什么?
    $message_id = 6;
    
    $alert = new Alerts($message_id);
    echo $alert->output;
    
    echo $alert;