Objects inside of objects help.

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
cerberusstudios
Forum Newbie
Posts: 7
Joined: Tue Apr 20, 2010 2:39 am

Objects inside of objects help.

Post by cerberusstudios »

Hey everyone. I have been using php for a while and taught myself how to used it. My original language was C/C++ so sometimes I try to pull things in from that that just do not work. Anyway here is the problem I am not able to figure out. I have an object that handles all of my database logic for me but I am not able to create that object inside of another object (kind of like a self created variable) Does PHP not support this or is there a work around for this issue? Here is an example of what I am trying to do.

Code: Select all


class Data_Connection
{
//Some properties

//Some methods
}

class Sitelogic
{
private $Database_Connection = new Data_Connection;
}
Currently my Data_Connection works perfectly the way I want it to as long as it is not inside of another class. But trying to put this into a 3 tier model is just not working for me right now. Please help. Thanks a lot
User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

Re: Objects inside of objects help.

Post by Benjamin »

The syntax is a bit different. The __constructor will automatically be executed when the class is instantiated.

Code: Select all

class Data_Connection
{
//Some properties

//Some methods
}

class Sitelogic
{
    private $Database_Connection;

    public function __construct() {
        $this->Database_Connection = new Data_Connection();
    }
}
You can also do this:

Code: Select all

class Sitelogic
{
    private $Database_Connection;

    public function __construct(Data_Connection $Data_Connection) {
        $this->Database_Connection = $Data_Connection;
    }
}

$sl = new Sitelogic(new Data_Connection());
cerberusstudios
Forum Newbie
Posts: 7
Joined: Tue Apr 20, 2010 2:39 am

Re: Objects inside of objects help.

Post by cerberusstudios »

HAHA Thanks. I could have sworn that I tried to use the constructor to try to do that, but after I typed in that code it worked perfectly. Guess I just needed someone elses magic touch. Thanks again :)
Post Reply