2015-08-31 81 views
0

我试图用一个类的对象在另一个类(使用美孚的测试实例)不能创建在类的构造函数的对象

我初始化$ CLS作为富构造一个新的考验,预计$ cls可以在Foo实例中使用,但事实并非如此。

这里是我的尝试:

<?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; 

运行我得到这个错误后:

注意:试图让非对象

如果我再初始化CLS,将财产没事的。

为什么在构造函数中初始化$ cls不起作用?

+0

它应该是'$ this-> cls = new Test();' –

回答

1
//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; 
相关问题