2012-06-09 245 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

问题已更新。 –