Page 1 of 1

Objects inside of objects help.

Posted: Tue Apr 20, 2010 2:55 am
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

Re: Objects inside of objects help.

Posted: Tue Apr 20, 2010 3:00 am
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());

Re: Objects inside of objects help.

Posted: Tue Apr 20, 2010 3:09 am
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 :)