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();
}
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;
You have to instantiate the
Animalsobject after you create$dbh, otherwise it’s not defined in theget_fields()function.That being said, a better design is to use dependency injection, and send the
$dbhobject to the class, like this:So, your updated class would look like:
The benefit? You get rid of the
globalvariable. 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.