我知道这可能是一个重复的帖子,但是所有的例子都没有帮助我,像this这样的例子我试图将我的数据库连接传递给用户类。
我做错了什么
我收到了以下错误
Undefined property: Db::$connect
Call to a member function prepare() on a non-object
db.php中
<?php
error_reporting(-1);
class Db{
private $db_host;
private $db_user;
private $db_name;
private $db_pass;
public function connect()
{
$this->db_host = "127.0.0.1";
$this->db_user = "root";
$this->db_pass = "root";
$this->db_name = "eli9";
try {
$db = new PDO("mysql:host=127.0.0.1;port=8889,dbname=eli9", 'root', 'root');
$db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
echo "connected \n";
}
catch (PDOException $e){
echo $e->getMessage();
}
return $db;
}
}
user.php的
<?php
require_once 'Db.php';
class User extends Db{
private $db;
public function __construct()
{
$this->db = new Db();
}
public function signup($email, $password, $username)
{
try{
$stmt = $this->db->connect->prepare("INSERT INTO users (user_email, user_pass, user_name) VALUES (:email, :password, :username) ");
$stmt->bindparam(':email', $email);
$stmt->bindparam(':password', $password);
$stmt->bindparam(':username', $username);
$stmt->execute();
}
catch(PDOExeception $e)
{
echo $e->getMessage();
}
}
}
答案 0 :(得分:2)
我可能错了,但我认为您不能创建扩展DB类的用户类,然后在构造函数中使用DB类连接函数。
您的用户类应继承您应该能够使用的数据库连接,如
$this->db = $this->connect();
在你的构造函数中。