大家好,我的代码有问题。使用 __construct() 我收到致命错误:调用非对象上的成员函数 prepare() 但没有它我的代码正在工作。
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)与
public $animal_id;
public $animal_type;
public $animal_name;