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

发布于 2024-11-18 01:01:27 字数 663 浏览 4 评论 0原文

我有两个类,数据库和用户。在数据库类中,我有连接数据库的功能。我希望能够在 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()

I have two classes, Database and User. In the Database class I have function to connect to the database. I am wanting to be able to have a connection to the database within the User class. This is what I am currently doing in the User Class:

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'));
    }
}

I get the following error:

PHP Fatal error: Call to a member
function prepare() on a non-object

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

月下伊人醉 2024-11-25 01:01:27

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

纠正这个问题很容易。只需添加

class User {
   private $DBH;

并将 $DBH 更改为 $this->DBH。也可能有助于阅读 $this 和成员变量。

You should read about "scope." $DBH is only declared locally in __construct().

Rectifying this is easy. Simply add

class User {
   private $DBH;

and wherever you have $DBH change to $this->DBH. May help to read about $this and member variables as well.

〆凄凉。 2024-11-25 01:01:27

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

class User {

    private $dbh;

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

}

然后在其他类方法中,您可以使用 $this- 调用该对象>dbh

You would need to assign your $DBH to a class property to allow access in other class methods. Right now $DBH is local to __construct() and can't be used outside of it

class User {

    private $dbh;

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

}

Then in other class methods you would call that object with $this->dbh.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文