PHP 8 中的新特性 (二), Constructor property promotion

程式技術
sharkHead

Constructor property promotion,不知道怎麼翻譯,建構子屬性提升

首先先來一段 Code。

<?php

class TestClass
{
	public string $one
	public string $two
	
	// 建構子(別稱:構造函式)
	public function __construct(string $one = 'first', string $two = 'second')
	{
		$this->one = $one;
		$this->one = $two;
	}
}

echo (new TestClass())->one;

什麼是建構子?
從 PHP 5 開始,開發者可以在一個類中定義一個方法作為建構子 (構造函式),具有建構子的類會在每次創建新對象時先調用此方法,所以非常適合在使用對象之前做一些初始化工作。

From PHP 官方網站

這段程式碼執行的結果為。

first

如果以 PHP 8 重新改寫,我們可以改寫成。

<?php

class TestClass
{
	public function __construct(
		public string $one = 'first',
		public string $two = 'second'
	) {}
}

echo (new TestClass())->one;

又是一個精簡語法!

簡單來說,Constructor property promotion 就是整合 Class 屬性、建構子參數的定義、Class 屬性指定敘述,在使用 Value object 或是 Data transfer object 時可以更為精簡你的程式碼。

使用 Constructor property promotion 有一些地方需要注意,例如:

  • 只能使用在建構子。
  • 屬性名稱無法重複。
<?php

class TestClass
{
	public string $one;

	public function __construct(
		// 屬性名稱已重複
		public string $one = 'first',
	) {}
}
  • 不允許使用 new 語句。
public function __construct(
    public string $one = 'first',
    // 無法使用 new 語句
    public DateTimeImmutable $date = new DateTimeImmutable(),
) {}

參考資料

sharkHead
written by
sharkHead

後端打工仔,在下班後喜歡研究各種不同的技術。稍微擅長 PHP,並偶爾涉獵前端開發。個性就像動態語言般隨興,但渴望做事能像囉嗦的靜態語言那樣嚴謹。

0 則留言