您好我正在尝试创建一个用户类并使用该类来处理登录,但是由于某种原因,我的用户类构造函数正在将我的mysqli对象作为字符串读取
这是我的代码
Class.php
<?php
/**
*
*/
class user{
protected $email;
protected $password;
private $db;
protected $user;
function __construct(mysqli $db, $email, $password){
$this -> $db = $db;
$this -> $email = $email;
$this -> $password = $password;
}
protected function check(){
$query = 'SELECT * FROM user WHERE email =?';
$handler = $this -> $db -> prepare($query);
$handler -> execute(array($this->email));
if($handler -> num_rows() > 0){
$user = $handler -> fetch();
$submitpassword = ($this -> $password);
if ($submitpassword == $user['password']) {
return $user;
}
}
return false;
}
public function login(){
$user = $this->check();
if ($user) {
$this->_user = $user; // store it so it can be accessed later
$_SESSION['user_id'] = $user['id'];
return $user['id'];
}
return false;
}
public function getUser(){
return $this->_user;
}
}
?>
mysql.php
<?php
if (!isset($_POST['submit'])) {
echo 'Page not found';
exit();
}
$servername = "localhost";
$username = "root";
$password = "";
$db = "imagesite";
// Create connection
$conn = new mysqli($servername, $username, $password,$db);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
checklogin.php
<?php
include 'mysql.php';
include 'class.php';
// username and password sent from form
$email=$_POST['email'];
$pass=$_POST['password'];
$user = new user($conn, $email, $pass);
$id = $user -> login();
if ($id) {
echo 'Logged it as user id: '.$user_id;
}else{
echo 'did not work';
}
?>
它给了我这个错误
Catchable fatal error: Object of class mysqli could not be converted to string in C:\wamp\www\class.php on line 13
我用这个把头发拉出来,有什么想法吗?
答案 0 :(得分:0)
要使用实例属性,不需要美元符号。只需更改
function __construct(mysqli $db, $email, $password){
$this -> $db = $db;
$this -> $email = $email;
$this -> $password = $password;
}
对此:
function __construct(mysqli $db, $email, $password){
$this->db = $db;
$this->email = $email;
$this->password = $password;
}