PHP 中的嵌套继承
例如,我有这样的类:
class MyClassA{
protected $variableA='this is var A';
public $variableB='this is var B';
//some function here
}
class MyClassB extends MyClassA{
//some function here
}
class MyClassC extends MyClassB{
//some function here
}
class MyClassD extends MyClassC{
//some function here
}
How can I get $variableA
and $variableB
from MyClassD
?
For an instance, I have classes like this:
class MyClassA{
protected $variableA='this is var A';
public $variableB='this is var B';
//some function here
}
class MyClassB extends MyClassA{
//some function here
}
class MyClassC extends MyClassB{
//some function here
}
class MyClassD extends MyClassC{
//some function here
}
How can I get $variableA
and $variableB
from MyClassD
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
只需使用
$this
在任何类中引用它们即可。看看它是否有效!
Just reference them in any class using
$this
.See it work!
由于
variableA
在基类中是公共的,因此您可以直接访问它,如下所示:$MyClassDObj->variableB
。由于
variableA
是受保护的,如果你想从类外部访问它,你需要编写一个getter,否则从类D内部,你可以像variableB一样访问它。 getter 看起来像这样:然后你调用
$MyClassDObj->getVariableA()
;Since
variableA
is public in the base class, you can just access it directly like so:$MyClassDObj->variableB
.Since
variableA
is protected, you need to write a getter if you wanted to access it from outside the class, otherwise from within class D, you can access it just like variableB. A getter would look like this:And then you call
$MyClassDObj->getVariableA()
;就像您从 MyClassA 获取它一样。
Just like you'd get it from MyClassA.