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();

$barクラスから定義しFoo、 に拡張するAnotherBarためFoo、 からすでに定義されている変数を取得することを期待していますFoo

何が悪いのかわかりません。どこから始めますか?

ありがとう!

4

1 に答える 1

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、よりクリーンなソリューションとなる方法でこれを行うこともできます。

于 2012-06-09T01:27:44.360 に答える