可恢复的致命错误:类mysqli的对象无法转换为字符串

时间:2017-11-18 06:36:59

标签: php

把我的头撞在墙上一段时间了。我也阅读了大部分建议的问题。我试图将我的mysqli连接传递给类构造函数并将其设置为类变量并得到:可恢复的致命错误:类mysqli的对象无法转换为字符串

PHP:

$con=mysqli_connect("abc", "abc", "abc", "abc");
if (mysqli_connect_errno()) {
    echo "Failed to connect to MariaDB: " . mysqli_connect_error();
}
/* check connection */
if ($con->connect_errno) {
    printf("Connect failed: %s\n", $con->connect_error);
    exit();
}

$t = new Timer($con);
// lots of irrelevant code
unset($t);

class Timer {
    private $time = null;
    private $con;
    public function __construct($con) {
        $this->$con = $con;
        $this->time = time();
        echo 'Working - please wait..<br/>';
    }

    public function __destruct() {
        $basename = basename($_SERVER['PHP_SELF']);
        $query = "SELECT ScriptID FROM scripts WHERE `ScriptURL` = '$basename';";
        $scriptIDResult = mysqli_fetch_assoc(mysqli_query($con, $query)) or die(mysqli_error($con));
        $t->scriptID = $scriptIDResult['ScriptID']; 
        $elapsed = (time()-$this->time);
        echo '<br/>Job finished in '.($elapsed).' seconds.';
        $scriptQuery = "UPDATE `scriptruns` SET `ScriptExecutedTime` = '$elapsed', `ScriptRunDate` = NOW() WHERE `ScriptID` = '$scriptID'";
        $result = mysqli_query($con, $scriptQuery) or die(mysqli_error($con));
    }
}

$this->$con = $con;上的构造函数中抛出错误。

1 个答案:

答案 0 :(得分:4)

问题在于:

$this->$con = $con;

这只是一个错字,但让我们看看会发生什么。 $this->$con$this的属性,其名称存储在$con变量中。寻找名称,PHP尝试将$con转换为字符串; $con是类mysqli的对象(它不会实现__toString())这就是它触发&#34;类mysqli的对象无法实现的原因转换为字符串&#34; 错误消息。

显然,代码应为:

$this->con = $con;

您还会在__destruct()中收到错误消息。您设置的变量$con未设置为mysqli对象。在析构函数中应该是$this->con