0

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

2
  • Please read the PHP docs... they are a good read.... Commented Nov 5, 2013 at 18:43
  • 1
    Did you try to call a parent property and see what happens? Commented Nov 5, 2013 at 18:44

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

do I have to rewrite them ? something like on the child class : protected $db = parent::db, because on my child class i'll have to use something like $request = $this->db->prepare(insert request here);
no. your child class inherits protected $db. You can do $this->db-> ... in your child class as if it were declared in the child class itself, so long as you properly initialize it.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.