Mysqli 连接问题致命错误



我有以下代码:

class config_model
{
    public $host;
    public $root;
    public $root_password;
    public $db;
    public function __construct() {
        $this->host = "localhost";
        $this->root = "root";
        $this->root_password = "";
        $this->db = "Data";
    }
    public function init() {
        $mysqli = new mysqli($this->host, $this->root, $this->root_password, $this->db);
        if ($mysqli->connect_error) {
            die('Connect Error (' . $mysqli->connect_errno . ') '
                . $mysqli->connect_error);
        }
        return $mysqli;
    }
}
$config_model = new config_model();
echo $config_model->init();

当我检查脚本时,我看到此错误:

"可捕获的致命错误:类 mysqli 的对象无法转换为字符串"。

erorr在这里:"echo $config_model->init();"

如何处理此错误?

你的错误是这样的:

"可捕获的致命错误:类 mysqli 的对象无法转换为字符串"。

现在,阅读错误:它说类 mysqli 的对象未转换为字符串。实际阅读它。现在,我希望你知道什么是对象,我也希望你知道什么是字符串。因此,Object 位于正在转换为字符串的某个位置,并且对象无法处理该转换。

这是在哪里发生的?逐行读取代码,您甚至可以给出发生错误的行:

echo $config_model->init();

您正在回显一个对象,因为这是由 ->init() 方法调用返回的内容,Init 会返回一个对象类型。然后,您立即告诉 PHP 将此对象输出为字符串类型。导致了问题。

溶液

PHP 有一个__ToString()魔术方法,你可以把它添加到你的对象中,这样你称之为字符串的东西(你不应该,但是......)对象将运行这个魔术方法并输出你指定的东西。

更简单的解决方案也不是尝试将对象输出为字符串,而是使用诸如 print_rvar_dump 之类的例程(但如前所述,您根本不应该在完美的世界中这样做)。

代码$config_model->init()返回Config_model类的对象,所以你不能"回显"它,因为回显用于字符串,如果您想测试您的配置,您可以使用var_dump() .

例如:

$config_model = new config_model();
var_dump($config_model->init());
mysqli_report(MYSQLI_REPORT_STRICT);
try {
     $connection = new mysqli('localhost', 'my_user', 'my_password', 'my_db') ;
} catch (Exception $e ) {
     echo "Service unavailable";
     echo "message: " . $e->message;   // not in live code obviously...
     exit;
}

$config_model = new config_model();

$config_model 是对象,不能回显它,只需使用 var_dump() 即可。

相关内容

最新更新