以下を機能させようとしていますが、途方に暮れています...
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 クラスのインスタンスを作成することです。これは を使用して機能し=&
ます。しかし、クラス Foo をクラス Bar で拡張すると、子はすべてのデータ属性とメソッドを親クラスから継承すると思いました。ただし、$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 クラスの新しいインスタンスを作成する必要がありますか? または、何か不足していますか?
よろしくお願いします。