簡體   English   中英

Mysqli連接問題致命錯誤

[英]Mysqli connection issue fatal error

我有以下代碼:

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類的對象未轉換為string 實際閱讀它。 現在,我希望您知道什么是對象,也希望您知道什么是字符串。 因此,對象在某處被轉換為字符串,並且該對象無法處理該轉換。

這是哪里發生的? 一行一行地讀取代碼,甚至給出錯誤發生的行:

echo $ config_model-> init();

你是呼應了一個對象,因為這是正在被版由->init()方法調用,init的給你回的對象類型。 然后,您立即告訴PHP將這個對象輸出為字符串類型。 是引起問題的原因。

PHP有一個__ToString()魔術方法 ,您可以將其添加到對象中,以便您將其稱為字符串(不應該,但是...),該對象將運行此魔術方法並輸出您指定的內容。

一個更簡單的解決方案也不是嘗試將對象輸出為字符串,而是在確實需要時使用諸如print_rvar_dump例程(但如上所述,您完全不應該在理想環境中這樣做)。

代碼$config_model->init()返回Config_model類的對象,因此您不能“回顯”它,因為echo用於字符串。如果要測試配置,則可以使用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 =新的config_model();

$ config_model是對象,無法回顯它,只需使用var_dump()。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM