如何在类中使用全局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");
它给了我错误:
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
解决方法:
你必须以某种方式将$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 );
这基本上是一种称为依赖注入的模式.有关这是什么的更多信息,请参见this excellent tutorial.
标签:php,class,object,global
来源: https://codeday.me/bug/20190726/1544611.html