2012-06-09 243 views
0

我有以下代碼,我希望返回「WORKED」,但不返回任何內容。類層次結構

class Foo { 
    public function __construct() { 
     echo('Foo::__construct()<br />'); 
    } 

    public function start() { 
     echo('Foo::start()<br />'); 

     $this->bar = new Bar(); 
     $this->anotherBar = new AnotherBar(); 
    } 
} 

class Bar extends Foo { 
    public function test() { 
     echo('Bar::test()<br />'); 

     return 'WORKED'; 
    } 
} 

class AnotherBar extends Foo { 
    public function __construct() { 
     echo('AnotherBar::__construct()<br />'); 

     echo($this->bar->test()); 
    } 
} 

$foo = new Foo(); 
$foo->start(); 

路由器

Foo::__construct() <- From $foo = new Foo(); 
Foo::start() <- From Foo::__construct(); 
Foo::__construct() <- From $this->bar = new Bar(); 
AnotherBar::__construct() <- From $this->anotherBar = new AnotherBar(); 

因爲我定義$barFoo類,並延伸到AnotherBarFoo,我希望得到來自Foo已定義的變量。

我看不出有什麼問題。我開始在哪裏凸輪?

謝謝!

回答

3

AnotherBar實例從來沒有調用它的start方法,所以它的$this->bar未定義。

有錯誤的顯示您會收到以下消息:

Notice: Undefined property: AnotherBar::$bar in - on line 20 
Fatal error: Call to a member function test() on a non-object in - on line 20 

可以包括<?php你行後右下面的代碼,看到所有的錯誤:

ini_set('display_errors', 'on'); 
error_reporting(E_ALL); 

當然你也可以通過php.ini這樣做,這將是一個更清潔的解決方案。

+0

是的,我知道這個錯誤。將更新我的問題。 –

+0

問題已更新。 –