gpt4 book ai didi

PHP 可捕获 fatal error : Object of class could not be converted to string

转载 作者:可可西里 更新时间:2023-11-01 00:00:28 25 4
gpt4 key购买 nike

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

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

插入的方法非常简单:

// 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]);
}

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

[Tue Jul 30 22:34:44 2013] [error] [client 127.0.0.1] PHP Catchable fatal error: Object of class framework\models\Message could not be converted to string in /var/www/p-lug/p-lug_lib/framework/models/Message.php on line 18, referer: https://p-lug.localhost/message/compose/4

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

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

我在所有传递的变量上使用了 var_dump(),在 $this$sth 上,一切都检查过了。但是在 execute() 上它失败了。这到底是怎么回事?

最佳答案

所以 $message 包含一个对象。

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

然后,您将存储在变量 $body 中的 Message 对象存储在哈希数组中,该数组作为参数传递给执行。

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

所以要么声明

public function __toString() {
return $the_string;
}

或者创建另一个可以传递给执行函数的公共(public)函数/成员。

关于PHP 可捕获 fatal error : Object of class could not be converted to string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17961347/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com