如何在扩展类中访问父PHP类属性

时间:2014-06-05 18:27:03

标签: php class oop object

我尝试在其子类中访问父类属性,但我一直收到此错误 致命错误:未定义的类常量' arms'在blabla.php的第26行。 这是我在下面的代码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();


?>

如果我的代码中有错误,请告诉我以及如何纠正它。 提前谢谢。

1 个答案:

答案 0 :(得分:1)

你的语法错了。

ClassName::NAME

用于访问类常量,如错误消息所示。

使用类'body中的const关键字定义类常量。

但是,您想要访问对象的属性。您必须使用$this作为

在方法体内:$this->propertyName。您必须确保该属性对其子类可见,因此您需要使其受保护或公开,或者实现魔术__get方法或定义自定义getter和setter并调用它们而不是实际属性。

您也不要使用parent关键字。 parent始终查找父类的静态字段,并且通常不与实例绑定。 (但是,您可以使用它在子类的上下文中从父类调用方法)

相关问题