Page 1 of 1

Include Class inside another Class

Posted: Tue May 27, 2008 5:42 pm
by ykarmi
Hey Guys,
This is a pretty newbie question but my google keyword skills did not seem to help.
I am very new to OOP - I used to do everything procedural until not a long time ago.


I have a database class that I use to connect and talk to my database.
I have another class (user class) which is supposed to add a user to the database.
I need to somehow make my user class use the db class, and trying to include it with the __construct thing did not work...
This is what I tried

Code: Select all

 
class User{
    
    public $error;
    public $db;
    
    public function __construct(){
        require_once "db.class.php";
        $this->db = new DB;
    }
    
    public function create($username, $password){
        //...
    }
 
}
 
I use PHP5 and I have no idea how to do this in a way that is considered good practice.
Please help.
Thanks!
Yuval :D

EDIT: If I use 'extends' for the DB class (though it's not really extending it) will I be prevented from extending the User class?

Re: Include Class inside another Class

Posted: Tue May 27, 2008 8:31 pm
by Jonah Bron
Try this:

Code: Select all

include('db.class.php');
class User{
     public $error;
     public $db;
     public function __construct(){
         $this->db = new DB;
     }
     public function create($username, $password){
         //...
     }
}
And no, the fact that the DB class extends another class should not stop it.

Re: Include Class inside another Class

Posted: Tue May 27, 2008 9:59 pm
by Christopher
I think it is better to pass the DB object in:

Code: Select all

 
class User{
    
    public $error;
    public $db;
    
    public function __construct($db){
        $this->db = $db;
    }
    
    public function create($username, $password){
        //...
    }
}
ykarmi wrote:EDIT: If I use 'extends' for the DB class (though it's not really extending it) will I be prevented from extending the User class?
You can extend any class, even if it extends another class.