Dan
Dan

Reputation: 3

PHP5 Using a class within a class

I am trying to use a class within a class, but seem to be having an issue with the initialised content of the class. It can see the class structure fine if you do a var_dump, but it wont see the content you have initialised with. I know im probably missing something pretty obvious, any pointers would be great. An example is below...

class firstClass()
{

    public $thedate;

    function __construct()
    {
        $this->thedate = date();
    }

}


class secondClass()
{

    public $datefrom1stclass;

    function __construct()
    {
        $this->datefrom1stclass = new firstClass;

        echo $this->datefrom1stclass->thedate;

    }

}

Sorry if I have not explained very well, If I do a var_dump I get the following:

object(firstClass)#3 (1) { ["thedate"]=> NULL }

Any pointers would be appreciated!

Upvotes: 0

Views: 62

Answers (2)

Amit Sharma
Amit Sharma

Reputation: 1988

Here is the correct code :) Enjoy `

public $thedate;

function __construct()
{
    $this->thedate = date("Ymd");
}

}

class secondClass {

public $datefrom1stclass;

function __construct()
{
    $this->datefrom1stclass = new firstClass;

    echo $this->datefrom1stclass->thedate;

}

} $var = new secondClass(); var_dump( $var ); ?> `

Upvotes: 0

raina77ow
raina77ow

Reputation: 106365

You shouldn't call date() without any parameters: at least one (a format, as a string) should be given:

$this->thedate = date('D M j G:i:s T Y');

The rest of your code is correct (although I'd prefer new firstClass() form, with parentheses - it's more readable).

Upvotes: 1

Related Questions