我有以下代码,我希望返回"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();
因为我从Foo
类中定义了$bar
,并且AnotherBar
扩展到Foo
,所以我希望从Foo
中获取已经定义的变量。
我看不出出了什么问题。我从哪里开始?
谢谢!
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
做到这一点,这将是一个更干净的解决方案。