【发布时间】:2009-06-12 16:28:32
【问题描述】:
我正试图让以下工作,但我不知所措......
class Foo {
public $somethingelse;
function __construct() {
echo 'I am Foo';
}
function composition() {
$this->somethingelse =& new SomethingElse();
}
}
class Bar extends Foo {
function __construct() {
echo 'I am Bar, my parent is Foo';
}
}
class SomethingElse {
function __construct() {
echo 'I am some other class';
}
function test() {
echo 'I am a method in the SomethingElse class';
}
}
我想做的是在 Foo 类中创建 SomethingElse 类的实例。这使用=& 有效。但是当我用类Bar扩展类Foo时,我认为子类继承了父类的所有数据属性和方法。但是,$this->somethingelse 似乎在子类 Bar 中不起作用:
$foo = new Foo(); // I am Foo
$foo->composition(); // I am some other class
$foo->somethingelse->test(); // I am a method in the SomethingElse class
$bar = new Bar(); // I am Bar, my parent is Foo
$bar->somethingelse->test(); // Fatal error: Call to a member function test() on a non-object
那么,就不能这样继承吗?如果我想在那里使用它,我应该从类 Bar 中创建一个新的类 SomethingElse 实例吗?还是我错过了什么?
提前感谢您的帮助。
【问题讨论】:
-
您正在继承类 Foo,而不是您创建的类 Foo 的实例,它设置了其他内容。
-
如果您将 SomethingElse 设为单例,那么您将使用 SomethingElse::getInstance() 而不是构造函数——否则在任意两个实例之间,SomethingElse 实例将有所不同。
标签: php inheritance composition