如果没有构造方法,为什么子类不能访问父类属性


Why can a child class not access a parent class propety without a construct method?

这可能是基本知识,但我很好奇,因为我自己还不知道。为什么在PHP(当然还有其他语言)中,当使用类时,子类必须使用construct方法来访问父类的属性?如果这是不清楚的,我将包括一个例子。

    <?php
     class aClass
      {
       protected $aProperty = "Some value";
      }
     class aDifferentClass extends aClass
      {
       public $aDifferentProperty;
       public function __construct()
        {
         $this->$aDifferentProperty = $this->aProperty;
      }
    ?>//Works.

代替:

    <?php
     class aClass
      {
       protected $aProperty = "Some value";
      }
     class aDifferentClass extends aClass
      {
       public $aDifferentProperty = $this->$aProperty;
      }
    ?>//Doesn't work.

这不是需要构造函数的问题,而是你何时试图访问它的问题。类是对象的蓝图——当你试图分配属性时,就像你在上面的例子中所做的那样,即

public $aDifferentProperty = $this->aProperty;

没有对象,因此"这个"还不存在。但是,相反,这将工作:

class A {
  protected $a_property = "BOOYEA!";
}
class B extends A {
   public function show_me_a_prop() {
      echo $this->a_property;
   }
}
$object = new B();
$object->show_me_a_prop();

所以,为了回答你的问题,你必须等到对象被构造之后才能访问属性,因为在它被构造之前,它不是对象,只是一个对象的蓝图。

现在,更进一步说,不允许将变量直接赋值给属性(参见http://php.net/manual/en/language.oop5.properties.php),但可以赋值一个常量。下面是一个类似的例子:

class A {
  const a_property = "BOOYEA!";
}
class B extends A {
   public $b_property = self::a_property;
}
$object = new B();
echo $object->b_property;

"__construct"是在PHP5中引入的,它是定义构造函数的正确方式(在PHP4中,您使用类的名称作为构造函数)。

你不需要在你的类中定义构造函数,但是如果你希望在对象构造中传递任何参数,那么你需要一个。

也……如果您进一步更改子类继承的类,则不必更改对父类的构造调用。

更容易调用parent::__construct()而不是parent::ClassName(),因为它可以在类之间重用,并且可以轻松更改父类。