使用构造函数分配属性值和类声明中的属性分配有什么区别?

Moh*_*mar 4 php oop

使用构造函数分配属性值和在类声明中直接分配属性有什么区别?换句话说,下面两段为新对象设置默认值的代码有什么区别?

直接赋值的代码:

<?php
 class A {
   public $name="aName";
   public $weight = 80;
   public $age = 25;
   public $units = 0.02 ;
 }
?>
Run Code Online (Sandbox Code Playgroud)

带构造函数的代码:

<?php
 class A {
   public $name;
   public $weight;
   public $age;
   public $units;
   public function __construct() {
       $this->name = "aName";
       $this->weight = 80;
       $this->age = 25;
       $this->units= 0.02 ;
   }
 }
?>
Run Code Online (Sandbox Code Playgroud)

您可能会回答说我无法更改硬编码属性,但我可以使用以下代码(在本地服务器中):

<?php
  class A{
     public $name="aName";
     public $weight = 80;
     public $age = 25;
     public $units = 0.02 ;
  }
 class B extends A{
    public function A_eat(){
       echo $this->name.' '."is".' '.$this->age.' '."years old<br>";
       echo $this->name.' '."is eating".' '.$this->units.' '."units of food<br>";
       $this->weight +=$this->units;
       echo $this->name.' '."weighs".' '.$this->weight."kg";
     }
   }
  $b = new B();
  echo "<p>If no changes to the object's Properties it inherits the main class's</p>";
  $b->A_eat();
  echo '<br><br>';
  echo "<p>If changes made to the object's Properties it uses it's new properties</p>";
  $b->name ="bName";
  $b->weight = 90;
  $b->units = 0.05;
  $b->A_eat();
?>
Run Code Online (Sandbox Code Playgroud)

Rus*_*nov 5

当属性声明包含初始化时,初始化在编译时进行评估,即在 PHP 源代码编译为PHP 操作码的步骤中

构造函数中的代码在运行时进行评估,即在创建带有new运算符的对象时。

如果您不使用操作码缓存(OPcache、APC 和类似扩展),则实际上没有区别。但是,如果操作码被缓存,显然编译时初始化的性能会更好。