PHP 8 中的构造函数属性提升

phpserver side programmingprogramming更新于 2025/10/3 7:16:00

在 PHP 8 中,添加了构造函数属性提升。它有助于在构造简单对象时减少大量样板代码。此功能允许我们将类字段、构造函数定义和变量赋值(全部使用一种语法)组合到构造函数参数列表中。

我们可以说,我们可以使用构造函数属性提升将它们全部组合起来,而不是指定类属性和构造函数。

示例 1:PHP 7 代码

<?php
   class Account {
      public float $a;
      public float $b;
      public float $c;
      public function __construct(
         float $a = 0.0,
         float $b = 0.0,
         float $c = 0.0,
      )
      {
         $this->a = $x;
         $this->b = $y;
         $this->c = $z;
      }
   }
?>

示例 2:PHP 8 代码

我们可以用 PHP 8 重写上述 PHP 7 代码,如下所示 −

<?php
   class Account {
      public function __construct(

         public float $a = 0.0,
         public float $b = 0.0,
         public float $c = 0.0,
      ) {}
   }
   $Account =new Account (10.90,20.0,30.80);
      print_r($Account->a);
      print_r($Account->a);
      print_r($Account->a);
?>

输出

10.9 20 30.8

在上面的代码中,我们在构造函数签名中将属性定义和填充内联组合在一起。此代码将删除重复。

示例 3:用于构造函数属性提升的 PHP 8 代码

<?php
   class Employee {
      public function __construct(
         public int $id,
         public string $name,
      ) {}
   }
   $employee = new Employee(11, 'Alex');
      print_r($employee->id);
      print_r($employee->name);
?>

输出

11 Alex

相关文章