我试图从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
答案 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:
public
,private
或protected
范围。$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()
。