我试图从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类(连接)
    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

最佳答案

$this->$con;应该是$this->con;

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

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

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


和setter方法来设置属性值,例如

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


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

关于Don Don OO的其他提示:


提供属性范围,例如publicprivateprotected
$this->obj而不是$this -> obj
不要在自己的类中调用诸如getConnection()之类的getter方法。您可以只使用$this->con

09-09 19:55
查看更多