PHP 8 中的建構函式屬性提升


在 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 7 程式碼重寫為 PHP 8 程式碼 -

<?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

更新於: 2021 年 4 月 1 日

694 次瀏覽

職業起航

完成課程即可獲得認證

開始
廣告
© . All rights reserved.