Ale*_*lec 0 php inheritance composition
我正努力让以下工作,但我不知所措......
class Foo {
public $somethingelse;
function __construct() {
echo 'I am Foo';
}
function composition() {
$this->somethingelse =& new SomethingElse();
}
}
Run Code Online (Sandbox Code Playgroud)
class Bar extends Foo {
function __construct() {
echo 'I am Bar, my parent is Foo';
}
}
Run Code Online (Sandbox Code Playgroud)
class SomethingElse {
function __construct() {
echo 'I am some other class';
}
function test() {
echo 'I am a method in the SomethingElse class';
}
}
Run Code Online (Sandbox Code Playgroud)
我想要做的是在类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
Run Code Online (Sandbox Code Playgroud)
那么,以这种方式继承是不可能的?如果我想在那里使用它,我应该从类Bar中创建一个类SomethingElse的新实例吗?或者我错过了什么?
在此先感谢您的帮助.
我认为子进程从父类继承了所有数据属性和方法.
这是真的 - 子类从父类继承静态变量和静态方法.此外,任何子对象都将继承静态和实例变量和方法.
使用现有类结构获得所需内容的一种可能性是:
$bar = new Bar();
$bar->composition();// here you are calling the parent method, sets instance var $somethineelse
$bar->somethingelse->test();// now you can call methods
Run Code Online (Sandbox Code Playgroud)
在子实例中完成继承变量(在本例中为对象)的另一种方法是这样的:
class Foo {
protected $somethingelse;
public function __construct() {
$this->somethingelse = new SomethingElse();
}
}
class Bar extends Foo {
public function __construct() {
parent::__construct();
// now i've got $somethingelse
}
}
Run Code Online (Sandbox Code Playgroud)
有关PHP 5中类和对象的非常好的概述,请查看此处:http: //php.net/manual/en/language.oop5.php 确保全部阅读,如果OO是新的,可能需要几次为了你.