在PDO中的非对象上调用成员函数prepare() [英] Call to a member function prepare() on a non-object in PDO
问题描述
我的代码有问题.使用__construct()时出现致命错误:在非对象上调用成员函数prepare(),但没有它,我的代码可以正常工作.
Hi guys I am having problem with my code. with __construct() I am getting Fatal error: Call to a member function prepare() on a non-object but without it my code is working.
class Animals{
public $db_fields;
public function __construct(){
$this->db_fields = $this->get_fields();
foreach($this->db_fields as $field){
$this->$field = "";
}
public function get_fields(){
global $dbh;
$q = $dbh->prepare("DESCRIBE animals");
$q->execute();
$db_fields = $q->fetchAll(PDO::FETCH_COLUMN);
return $db_fields;
}
}
$f = new Animals();
/*** mysql hostname ***/
$hostname = 'localhost';
/*** mysql username ***/
$username = 'root';
/*** mysql password ***/
$password = '';
/*** mysql database***/
$dbname = 'animals';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);
/*** echo a message saying we have connected ***/
echo 'Connected to database <br />';
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
我只想让我的字段(animal_id,animal_type,animal_name)与
I just want to make my fields(animal_id,animal_type,animal_name) work as same as
public $animal_id;
public $animal_type;
public $animal_name;
推荐答案
创建$dbh
之后,您必须实例化Animals
对象 ,否则在get_fields()
函数中未定义该对象
You have to instantiate the Animals
object after you create $dbh
, otherwise it's not defined in the get_fields()
function.
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);
$f = new Animals();
话虽这么说,一种更好的设计是使用依赖项注入,然后将$dbh
对象发送给类,如下所示:
That being said, a better design is to use dependency injection, and send the $dbh
object to the class, like this:
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);
$f = new Animals( $dbh);
因此,您更新后的类如下:
So, your updated class would look like:
class Animals{
private $dbh;
public function __construct( $dbh){
$this->dbh = $dbh;
}
public function get_fields(){
$q = $this->dbh->prepare("DESCRIBE animals");
}
}
好处?您摆脱global
变量.通常,要求使用全局变量是一个错误的设计,因此您要避免使用它.您可以看到为什么仅根据您遇到的问题-它需要设置一个全局状态才能起作用.
The benefit? You get rid of the global
variable. Typically, requiring a global variable is a bad design, and you want to avoid it. You can see why just based on the problem you're having - It requires a global state to be set in order to function.
这篇关于在PDO中的非对象上调用成员函数prepare()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!