在 PHP 的类中使用全局 DB 变量
如何在类中使用全局数据库变量? 假设我的 config.php 中有这个
$dbh = new PDO("mysql:host=localhost;dbname=mydb", "root", "");
,我想在类内使用这个 $dbh ,如下所示 (MyClass.php)
class MyClass
{
public function DoSomething($plogin_id)
{
$sql = "SELECT * FROM mytable WHERE login_id = :login_id";
$stmt = $dbh->prepare($sql); //line 14
$stmt->bindParam(':login_id', $plogin_id, PDO::PARAM_STR);
}
}
在我的 index.php 文件中,我使用这个 MyClass 如下:
include "config.php";
$MyObject = new MyClass();
$login_result = $MyObject->DoSomething("admin");
它给了我错误:
致命错误:调用成员函数 在非对象上准备() C:\xampp\htdocs\MyProject\admin\includes\classes\MyClass.php 第 14 行
How can I use global DB variable inside class?
Let's say I have this in my config.php
$dbh = new PDO("mysql:host=localhost;dbname=mydb", "root", "");
and I want to use this $dbh inside class as follows (MyClass.php)
class MyClass
{
public function DoSomething($plogin_id)
{
$sql = "SELECT * FROM mytable WHERE login_id = :login_id";
$stmt = $dbh->prepare($sql); //line 14
$stmt->bindParam(':login_id', $plogin_id, PDO::PARAM_STR);
}
}
And inside my index.php file I am using this MyClass as follows:
include "config.php";
$MyObject = new MyClass();
$login_result = $MyObject->DoSomething("admin");
It is giving me error:
Fatal error: Call to a member function
prepare() on a non-object in
C:\xampp\htdocs\MyProject\admin\includes\classes\MyClass.php
on line 14
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您必须以某种方式将
$dbh
对象传递给MyClass
。由于您不想使用全局变量,因此我建议您将其传递给MyClass
的构造函数。您的 MyClass 和 index.php 可能看起来像这样:
这基本上是一种称为依赖注入的模式。请参阅这篇出色的教程了解有关内容的更多信息这是。
You have to pass the
$dbh
object toMyClass
somehow. Since you don't want to use globals, I suggests you pass it toMyClass
's constructor.Your MyClass and index.php could look something like this:
This is basically a pattern called dependency injection. See this excellent tutorial for more info on what this is.
您可以通过使用以下方式将其引入到您的函数中:
但是,将其添加到类中可能是一个更好的主意,如下所示:
然后:
或者,在调用时将其引入到您的函数中:
然后:
You can introduce it into your function by using:
However, it might be a better idea to add it to the class, like this:
and then:
Or, introduce it into your function at call time:
And then:
这是最常见的方法:
替代方法:
为数据库连接。您可以使用它而不是全局变量:
This is the most common method:
Alternative approach:
Create a singleton for the database connection. And you use that instead of a global variable: