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

时间:2014-07-03 12:22:28

标签: php mysql oop

我试图从OOP开始,因为它似乎比我习惯代码的方式要好得多,但现在我正在尝试创建一个mysql连接类,我一遍又一遍地收到同样的错误。

我使用2个类1进行连接,另一个用于查询。

班级用户(查询)

class Users{
protected $_userid, $_username, $_lastLogged, $_rank, 
$_driverLicense, $_experience, $_maxExperience, 
$_cash, $_vehicle, $_residence, $_weapon, $_tool, 
$_memberSince, $_about;

var $con;

function getConnection($con){
    return $this->$con;
}

function checkLogin($username, $password){
    $stmtCheckLogin = $this -> getConnection() -> prepare('SELECT `id`, `password` FROM `tbl_users` WHERE `username` = ? ');
    $stmtCheckLogin -> bind_param('s', $username);
    $stmtCheckLogin -> execute();
    $stmtCheckLogin -> bind_result($id, $password);
    $stmtCheckLogin -> store_result();
    $stmtCheckLogin -> fetch(); // just a test to see if everything is working correctly
    echo $id. "<br/>";
    echo $password;
}

 }

类db(连接)     class db {

function getCon(){
    $con = new mysqli('127.0.0.1', 'root', '', 'mafioso');
    if(!$con){
        throw new Exception('Could not connect to database..');
    }else{
        return $con;
    }
}

function __destruct(){
    $this -> getCon() -> close();
}
}

这就是我试图称呼它们的方式

<?php require_once('classes/User.php'); require_once('classes/db.php');

    $db = new db;
    $user = new Users();
    $user -> getConnection($db -> getCon());
    if(!isset($_SESSION['checkLogin']) || ($_SESSION['checkLogin'] == 0)){


    if(isset($_POST['login'])){
        $user -> checkLogin($_POST['username'], $_POST['password']);
    }
    ?>

这是我一直收到的错误:

 Catchable fatal error: Object of class mysqli could not be converted to string in classes\User.php on line 12

3 个答案:

答案 0 :(得分:4)

$this->$con;应为$this->con;

整个方法似乎是一个不起作用的getter / setter混合。

有getter方法可以获得如下属性:

function getConnection() {
    return $this->con;
}

和setter方法设置属性的值,如

function setConnection($con) {
    return $this->con = $con;
}

$this是您目前所在的课程。使用->,您可以解决方法和/或属性。但是,您不需要再次编写$,因为$this->已经暗示它是变量或方法。

其他暗示OO:

  • 为您的属性提供publicprivateprotected范围。
  • 撰写$this->obj而不是$this -> obj
  • 不要在自己的班级中调用像getConnection()这样的getter方法。您可以使用$this->con代替

答案 1 :(得分:2)

问题来自getConnection方法:

function getConnection($con){
    return $this->$con;
}

这将返回名称为$con的属性。 即如果$con = 'foo';,则此方法将返回$this->foo

在您的情况下,PHP正在尝试将连接转换为字符串,以便它可以访问相应的属性。 mysqli对象无法转换为字符串,因此会抛出致命错误。

可能你想要一个正确设置连接的setConnection和一个返回con。

的getConnection

尝试:

function getConnection(){
    return $this->con;
}
function setConnection($con){
    $this->con = $con;
}

答案 2 :(得分:2)

这段代码错了:

function getConnection($con)
{
    return $this->$con;
}

因为你给了getConnection一个mysqli-instance。所以在$this->$con中它试图将$con转换为字符串,但$con是一个mysqli实例。

也许你想要这样的东西:

function setConnection($con)
{
    $this->con = $con;
}

function getConnection()
{
    return $this->con;
}

因为您在$this->getConnection()中使用了checkLogin()