Aufruf einer Member-Funktion prepare () für ein Nicht-Objekt in PDO

Hallo Leute, ich habe ein Problem mit meinem Code. with __construct () Ich erhalte den schwerwiegenden Fehler: Rufe eine Mitgliedsfunktion prepare () für ein Nicht-Objekt auf, aber ohne sie funktioniert mein Code.

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();
}

Ich möchte nur, dass meine Felder (animal_id, animal_type, animal_name) genauso funktionieren wie

public $animal_id;
public $animal_type;
public $animal_name;

Antworten auf die Frage(1)

Ihre Antwort auf die Frage