[英]How to access parent PHP class properties in extended classes
I tried accessing parent class properties in its daughter class but I keep getting this error Fatal error: undefined class constant 'arms' on line 26 of blabla.php. 我尝试访问其子类中的父类属性,但始终收到此错误致命错误:blabla.php的第26行上的未定义类常量“ arms”。 This is my code below in blabla.php
这是我在blabla.php中的代码
blabla.php blabla.php
<?php
class mother
{
public $legs;
public $arms;
public $eyes;
function say($arm,$eye,$leg)
{
$this->arms = 'pretty';
$this->eyes = 'stunning';
$this->legs = 'beautiful slim';
}
}
class daughter extends mother
{
public $newArms;
public $newEyes;
public $newLegs;
public function newSay()
{
$this->newArms = parent::arms;
$this->newEyes = parent::eyes;
$this->newLegs = parent::legsparent::arms;
echo 'I have a beautiful daughter who has '.$this->newArms.' arms, '.$this->newEyes.' eyes and '.$this->newLegs.' legs';
}
}
$baby = new daughter();
$baby->newSay();
?>
if there is a mistake in my code, please show me and how to correct it. 如果我的代码有误,请向我展示如何纠正。 Thanks in advance.
提前致谢。
You got your syntax wrong. 您的语法有误。
ClassName::NAME
is used to access class constants as your errormessage says. 如您的错误消息所述,用于访问类常量。
A class constant is defined using the const
keyword in the class' body. 使用类主体中的
const
关键字定义类常量。
However, you want to access the property of an object. 但是,您要访问对象的属性。 You have to use
$this
for that 您必须使用
$this
Inside a methods body: $this->propertyName
. 在方法体内:
$this->propertyName
。 You have to make sure that the property is visible to its child classes, so you either need to make it protected or public or have the magic __get
method implemented or have custom getters and setters defined and call them instead of the actual property. 您必须确保该属性对其子类可见,因此您要么需要对其进行保护或公开,要么要实现魔术
__get
方法,或者定义自定义的getter和setter并调用它们而不是实际的属性。
You also don't use the parent
keyword for this. 您也不要为此使用
parent
关键字。 parent
always looks for static fields of the parent class and is generally not tied to an instance. parent
始终在寻找父类的静态字段,并且通常不绑定到实例。 (You can however use it to call a method from the parent class in the context of its child class) (但是,您可以使用它在其子类的上下文中从父类调用方法)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.