adaba
adaba

Reputation: 384

PHP OOP : Accessing parent attributes from child / Child inheriting from parent's attributes

so the code is : DAO class

    abstract class DAO  
    {   
    protected $db; 
    protected $SQL_host='localhost';
    protected $SQL_port='3306';
    protected $SQL_dbname='projet'; 
    protected $SQL_login='root'; 
    protected $SQL_password='';

    protected function __construct()
    {
        $this->setDb(new PDO('mysql:host='.$this->SQL_host.';port='.$this->SQL_port.';dbname='.$this->SQL_dbname, $this->SQL_login, $this->SQL_password)) ;
    }

    protected function setDb(PDO $bdd)
    {
        $this->db = $bdd ;
    }


    }

and child UserDAO class

     class UserDAO extends DAO 
     {
     public function __construct()
     {
         parent::__construct();
     }
     }

When UserDAO child class inherits from parent DAO, does the child get parent's attributes ? If not, how can I make so ?

I've been looking around and they mostly tell to use get function but that's really not what i'm trying to do. Thanks for your help

Upvotes: 0

Views: 105

Answers (2)

Joao
Joao

Reputation: 2746

I had the same issue as yourself. I wanted child classes to inherit the database pdo instance. The problem was, if I had multiple models ("users" and "documents" for example), it ended up creating multiple pdo instances (super wasteful). I resorted to dependency injection. I created the instance outside the class, then passed it to any class that needed pdo:

class UserDAO extends DAO 
{
     public function __construct($db=NULL)
     {
         if($db){//if database is requested
        parent::__construct($db);
    }
     }
}

There are loads of arguments for or against dependency injection - but I found this to work the most efficiently for myself.

In answer to your question, it seems you're doing it right (though, like I said, with PDO it might not be the best). Make sure both classes are included in your script.

Upvotes: 1

Madbreaks
Madbreaks

Reputation: 19549

Yes, the subclass inherits the parent class's members.

Upvotes: 2

Related Questions