我试着让下面的工作,但我不知道…
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似乎不能在子类栏中工作:
$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,我应该在其中创建一个新的实例吗?还是我错过了什么?
提前感谢您的帮助。
发布于 2009-06-12 16:51:15
我认为子类继承了父类的所有数据属性和方法。
这是真的-子类从父类继承静态变量和静态方法。此外,任何子对象都将继承静态和实例变量和方法。
通过现有的类结构获得您想要的内容的一种可能性是:
$bar = new Bar();
$bar->composition();// here you are calling the parent method, sets instance var $somethineelse
$bar->somethingelse->test();// now you can call methods在子实例中继承变量(在本例中为对象)的另一种方法如下所示:
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
}
}要对PHP5中的类和对象有一个非常好的概述,请看这里:http://php.net/manual/en/language.oop5.php请确保阅读所有内容,如果您对OO还不熟悉,可能会读几次。
发布于 2009-06-12 16:35:03
bar有一个名为somethingelse的成员变量,它是从foo继承的。
你混合了对象和类的作用域。
如果你真的想要达到所描述的效果,你必须使你的变量成为静态的,这样它的上下文就是基于类的
发布于 2009-06-12 17:21:00
首先,您必须区分静态变量和实例变量。静态变量在类的所有实例之间共享,而实例变量则不是。
如果你想让Foo和Bar的每个实例都有完全相同的SomethingElse-Instance,你必须让$somethingelse成为静态的:
公共静态$somethingelse
并且您应该更改Foo的组合函数:
function composition() {
self::$somethingelse = new SomethingElse();
}要访问这个静态字段,您可以执行以下操作:$foo = new Foo();//我是Foo $foo->composition();//我是其他类Foo:$ SomethingElse >test();//我是SomethingElse类中的一个方法
$bar = new Bar();//我是Bar,我的父类是Foo Bar::$ SomethingElse ->test();//我是SomethingElse类中的一个方法
如果希望Foo和Bar的每个实例都有自己的SomethingElse实例,可以使用您的代码,但需要添加
$bar->组合()
在$bar->somethingelse>test()之前;
那是因为
$bar =新的栏();
您创建了一个全新的Bar实例,该实例具有$somethingelse属性,但尚未设置该属性。因此,您需要调用composition()来设置它。
如果每个Foo和Bar都应该有完全相同的SomethingElse-instance,那么您应该使用静态版本,因为它减少了所需的内存。
我希望这能对你有所帮助。除此之外,我很乐意进一步解释它。
https://stackoverflow.com/questions/987651
复制相似问题