Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/278.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 在另一个类中自动加载数据库类?_Php_Database_Class_Constructor_Autoload - Fatal编程技术网

Php 在另一个类中自动加载数据库类?

Php 在另一个类中自动加载数据库类?,php,database,class,constructor,autoload,Php,Database,Class,Constructor,Autoload,我有两个类,数据库和用户。在数据库类中,我有连接到数据库的函数。我希望能够连接到用户类中的数据库。这就是我目前在用户类中所做的: class User { function __construct() { require_once 'database.class.php'; $DBH = new Database(); $DBH->connect(); } function register_user()

我有两个类,数据库和用户。在数据库类中,我有连接到数据库的函数。我希望能够连接到用户类中的数据库。这就是我目前在用户类中所做的:

class User {

    function __construct() 
    {
        require_once 'database.class.php';
        $DBH = new Database();
        $DBH->connect();
    }

    function register_user()
    {
        $DBH->prepare('INSERT INTO users VALUES (:username, :password, :forename, :surname)');
        $DBH->execute(array(':username' => 'administrator', ':password' => '5f4dcc3b5aa765d61d8327deb882cf99', ':forename' => 'Richie', ':surname' => 'Jenkins'));
    }
}
我得到以下错误:

PHP致命错误:调用成员 非对象上的函数prepare()

您应该阅读有关“范围”的内容。
$DBH
仅在
\uu construct()
中本地声明

纠正这一点很容易。简单地加上

class User {
   private $DBH;

无论在哪里,只要你有
$DBH
,就换成
$this->DBH
。阅读有关
$this
以及成员变量的信息可能会有所帮助。

您需要将
$DBH
分配给类属性,以允许在其他类方法中进行访问。现在,
$DBH
\uu construct()
的本地对象,不能在其外部使用

class User {

    private $dbh;

    public function __construct() {
        ... // your code
        $this->dbh = $DBH;
    }

}

然后在其他类方法中,您将使用
$this->dbh

调用该对象,我收到以下错误:PHP致命错误:调用未定义的方法Database::prepare(),这意味着
数据库
类没有名为
prepare()
的方法。它的实现是什么?我有点困惑,为什么我不能使用PDO prepare函数?@ritch那么你就必须使用PDO了