我试图让下面的工作,但我不知所措......PHP5类:继承一个组合类吗?
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';
}
}
我希望做的是创造SomethingElse的一个实例班级内的班级。这可以使用=&
。但是当我用class Bar扩展Foo类时,我认为子继承了父类的所有数据属性和方法。然而,似乎$this->somethingelse
不子类酒吧工作:
$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设置的不是实例。 – cloudhead 2009-06-12 16:33:45