Arashdn
Arashdn

Reputation: 731

Can't create an object in class constructor

I trying to use an object of a class in another class (using an instance of Test in Foo )

I initialize $cls as a new Test on Foo constructor , And It's expected $cls be ready to use in Foo instance , but It's not.

Here is what I tried:

<?php
class Test
{

    function __construct()
    {

    }
    public $str = "Arash";
}

class Foo
{

    function __construct()
    {
        $cls = new Test();
    }

    public $cls;

}



$ttt = new Foo();
$mmm =  $ttt->cls;
//$mmm = new Test(); //if I uncomment this line , every thing will work well
echo $mmm->str;

After running I got this error:

Notice: Trying to get property of non-object

If I initialize cls again , It will be fine.

Why Initializing $cls in constructor is not working?

Upvotes: 0

Views: 108

Answers (1)

Sachin Tyagi
Sachin Tyagi

Reputation: 143

//hey check it here is your code.
<?php
class Test
{
    public $str = "Arash";
    function __construct()
    {

    }

}

class Foo
{
    public $cls;
    function __construct()
    {
        $this->cls = new Test();
    }



}



$ttt = new Foo();
$mmm =  $ttt->cls;
//$mmm = new Test(); //if I uncomment this line , every thing will work well
echo $mmm->str;

Upvotes: 1

Related Questions