在PHP中的类中使用全局DB变量 [英] using global DB variable inside classes in PHP
问题描述
如何在类中使用全局数据库变量?
假设我在我的config.php中有这个
$ dbh = new PDO(mysql:host = localhost ; dbname = mydb,root,);
并且我想在类中使用这个$ dbh如下(MyClass.php)
class MyClass
{
public function DoSomething($ plogin_id)
{
$ s $ = 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如下:
includeconfig.php;
$ MyObject = new MyClass();
$ login_result = $ MyObject-> DoSomething(admin);
它给我错误:
致命错误:调用成员函数
对
中的非对象执行prepare()C:\ xampp\htdocs\MyProject\admin\includes\\ \\ classes \MyClass.php
第14行
将 $ dbh
对象传递给 MyClass
。由于你不想使用全局变量,我建议你将它传递给 MyClass
的构造函数。
您的MyClass和index.php可能如下所示:
class MyClass
{
protected $ dbh = null;
public function __construct(PDO $ Pdh)
{
$ this-> dbh = $ Pdh;
}
public function DoSomething($ plogin_id)
{
$ sql =SELECT * FROM mytable WHERE login_id =:login_id;
$ stmt = $ this-> dbh-> prepare($ sql); // line 14
$ stmt-> bindParam(':login_id',$ plogin_id,PDO :: PARAM_STR);
}
}
// in your index.php
$ MyObject = new MyClass($ dbh);
这基本上是一种称为依赖注入的模式。有关这是什么的更多信息,请参见这个出色的教程。 p>
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
You have to pass the $dbh
object to MyClass
somehow. Since you don't want to use globals, I suggests you pass it to MyClass
's constructor.
Your MyClass and index.php could look something like this:
class MyClass
{
protected $dbh = null;
public function __construct ( PDO $Pdh )
{
$this->dbh = $Pdh;
}
public function DoSomething($plogin_id)
{
$sql = "SELECT * FROM mytable WHERE login_id = :login_id";
$stmt = $this->dbh->prepare($sql); //line 14
$stmt->bindParam(':login_id', $plogin_id, PDO::PARAM_STR);
}
}
// in your index.php
$MyObject = new MyClass ( $dbh );
This is basically a pattern called dependency injection. See this excellent tutorial for more info on what this is.
这篇关于在PHP中的类中使用全局DB变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!