私が何をしたいのですが私は仕事に以下を取得しようとしているが、私は途方に暮れてよ...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のインスタンスを作成することですクラスFoo内のクラス。これは=&
を使用して動作します。しかし、クラスFooをクラスBarで拡張すると、子クラスは親クラスからすべてのデータ属性とメソッドを継承すると考えました。しかし、それは$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
だから、このように継承することができないのですか?クラスバーの中からSomethingElseクラスの新しいインスタンスを作成する必要がありますか?または私は何かを逃していますか?
ご協力いただきありがとうございます。
あなたはsomethingelseセットを持ってFooクラス、あなたが作成したクラスはFooのないインスタンスを、継承されています。 – cloudhead
SomethingElseをシングルトンにすると、コンストラクタの代わりにSomethingElse :: getInstance()を使用します。そうでなければ、SomethingElseインスタンスが異なる任意の2つのインスタンス間で使用します。 –