在另一个类中自动加载数据库类?
我有两个类,数据库和用户。在数据库类中,我有连接数据库的功能。我希望能够在 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该阅读有关“范围”的内容。
$DBH
仅在__construct()
中本地声明。纠正这个问题很容易。只需添加
并将
$DBH
更改为$this->DBH
。也可能有助于阅读$this
和成员变量。You should read about "scope."
$DBH
is only declared locally in__construct()
.Rectifying this is easy. Simply add
and wherever you have
$DBH
change to$this->DBH
. May help to read about$this
and member variables as well.您需要将
$DBH
分配给类属性,以允许在其他类方法中进行访问。现在$DBH
是__construct()
的本地对象,不能在其外部使用然后在其他类方法中,您可以使用
$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 itThen in other class methods you would call that object with
$this->dbh
.