PHP Catchable致命错误:类的对象无法转换为字符串

mis*_*tin 3 php pdo

我在这里完全迷失了...在验证了一些输入后,我创建了一个Message类的实例并尝试将数据插入到数据库中:

// send message
$message = $this->model->build('message', true);
$message->insertMessage($uid, $user->user_id, $title, $message);
Run Code Online (Sandbox Code Playgroud)

插入方法非常简单:

// insert a new message
public function insertMessage($to_id, $from_id, $title, $body)
{
    $sql = "INSERT INTO messages (to_id, from_id, title, body, create_date) VALUES
                                 (:to_id, :from_id, :title, :body, NOW())";
    $sth = $this->db->prepare($sql);
    return $sth->execute([':to_id' => $to_id, ':from_id' => $from_id, ':title' => $title, ':body' => $body]);
}
Run Code Online (Sandbox Code Playgroud)

但是,提交后我最终得到一个空白页面,Apache错误日志说:

[Tue Jul 30 22:34:44 2013] [错误] [client 127.0.0.1] PHP Catchable致命错误:类框架\ models\Message的对象无法转换为/ var/www/p-lug/p中的字符串第18行的-lug_lib/framework/models/Message.php,referer:https://p-lug.localhost/message/compose/4

第18行引用return语句,但即使我删除return它也会导致相同的错误.

我已经阅读了关于此错误的无数链接,但没有一个答案似乎适用于我的示例.在任何时候我都没有尝试将对象转换为字符串或输出结果,并且类似的插入与其他类的代码完美地工作.实际上,这段代码是从另一个工作示例中复制粘贴的,唯一改变的是表和数据.

我已经使用var_dump()了所有传递的变量,on $this$sth,一切都检查出来.但execute()就此失败了.到底发生了什么事?

Log*_*phy 12

所以$ message包含一个对象.

该对象作为第4个参数传递给函数insertMessage($ body仍然是同一个对象)

然后,将存储在变量$ body中的Message对象存储在散列数组中,该散列数组作为参数传递给execute.

execute函数尝试将Message对象转换为字符串,但发现没有声明__toString函数.

所以要么宣布

public function __toString() {
    return $the_string;
}
Run Code Online (Sandbox Code Playgroud)

或者创建另一个可以传递给execute函数的公共函数/成员.