PHP - 發現最新最好的

WBOY
發布: 2024-09-10 20:32:40
原創
728 人瀏覽過

PHP  - Discover the Latest and Greatest

PHP 8.4 計畫於 2024 年 11 月 21 日發布,包含一些令人興奮的新功能和改進。在這篇文章中,我們將探討一些最有趣的添加和更改:

  1. 新的陣列輔助函數
  2. 屬性掛鉤
  3. 不含括號的「新」
  4. 已棄用隱式可為空的參數宣告
  5. 新的多位元組函數

1.新的陣列輔助函數

PHP 8.4 中將會加入以下數組輔助函數變體:

  • array_find()
  • array_find_key()
  • array_any()
  • array_all()

這些函數將採用一個陣列和一個回呼函數並傳回以下內容:

functions Return value
array_find() Returns the first element that meets the callback condition; NULL otherwise.
array_find_key() Returns the key of the first element that meets the callback condition; NULL otherwise.
array_any() Returns true if at least one element matches the callback condition; false otherwise.
array_all() Returns true if all elements match the callback condition; false otherwise.

注意:array_find() 僅檢索第一個匹配元素。對於多個匹配,請考慮使用 array_filter()。

例子

給定一個包含鍵值對和回呼函數的陣列:

$array = ['1'=> 'red', '2'=> 'purple', '3' => 'green']

function hasLongName($value) {
  return strlen($value) > 4;
}
登入後複製

以下是我們如何使用新功能:

  1. array_find():

      // Find the first color with a name length greater than 4
    
      $result1 = array_find($array, 'hasLongName');
    
      var_dump($result1);  // string(5) "purple"
    
    登入後複製
  2. array_find_key():

      // Find the key of the first color with a name length greater than 4
    
      $result2 = array_find_key($array, 'hasLongName');
    
      var_dump($result2);  // string(1) "2"
    
    登入後複製
  3. array_any():

      // Check if any color name has a length greater than 4
    
      $result3 = array_any($array, 'hasLongName');
    
      var_dump($result3);  // bool(true)
    
    登入後複製
  4. array_all():

      // Check if all color names have a length greater than 4
    
      $result4 = array_all($array, 'hasLongName');
    
      var_dump($result4);  // bool(false)
    
    登入後複製

2. 屬性掛鉤

PHP 8.4 引入了屬性掛鉤,提供了一種更優雅的方式來存取和修改類別的私有或受保護屬性。以前,開發人員依賴 getter、setter 和魔術方法(__get 和 __set)。現在,您可以直接在屬性上定義 get 和 set 掛鉤,從而減少樣板程式碼。

我們可以使用程式碼區塊 {} 來包含屬性掛鉤,而不是用分號結束屬性。
這些鉤子是可選的,可以獨立使用。透過排除其中之一,我們可以使屬性只讀或只寫。

例子

class User
{
  public function __construct(private string $first, private string $last) {}

  public string $fullName {
    get => $this->first . " " . $this->last;

    set ($value) {
      if (!is_string($value)) {
        throw new InvalidArgumentException("Expected a string for full name,"
        . gettype($value) . " given.");
      }
      if (strlen($value) === 0) {
        throw new ValueError("Name must be non-empty");
      }
      $name = explode(' ', $value, 2);
      $this->first = $name[0];
      $this->last = $name[1] ?? '';
    }
  }
}

$user = new User('Alice', 'Hansen')
$user->fullName = 'Brian Murphy';  // the set hook is called
echo $user->fullName;  // "Brian Murphy"
登入後複製

如果 $value 是整數,則會拋出以下錯誤訊息:

PHP Fatal error:  Uncaught InvalidArgumentException: Expected a string for full name, integer given.
登入後複製

如果 $value 為空字串,則會拋出以下錯誤訊息:

PHP Fatal error:  Uncaught ValueError: Name must be non-empty
登入後複製

3. 不帶括號的“新”

PHP 8.4 引入了更簡單的語法,讓您在新建立的物件上連結方法而無需括號。雖然這是一個微小的調整,但它會帶來更乾淨、更簡潔的程式碼。

(new MyClass())->getShortName();  // PHP 8.3 and older
new MyClass()->getShortName();  // PHP 8.4
登入後複製

除了在新建立的物件上連結方法之外,您還可以連結屬性、靜態方法和屬性、陣列訪問,甚至直接呼叫類別。例如:

new MyClass()::CONSTANT,
new MyClass()::$staticProperty,
new MyClass()::staticMethod(),
new MyClass()->property,
new MyClass()->method(),
new MyClass()(),
new MyClass(['value'])[0],
登入後複製

4. 已棄用隱式可為 null 的參數聲明

在 PHP 8.4 之前,如果參數的類型為 X,它可以接受 null 值,而無需明確將 X 聲明為可為 null。從 PHP 8.4 開始,如果沒有在類型提示中明確聲明可為空,則不能再聲明空參數值;否則,將會觸發棄用警告。

function greetings(string $name = null)  // fires a deprecation warning
登入後複製

為了避免警告,您必須在類型聲明中使用問號 (?) 明確聲明參數可以為 null。

function greetings(?string $name)
登入後複製

或者,

function greetings(?string $name = null)
登入後複製

5.新的多位元組函數

多位元組字串是一個字元序列,其中每個字元可以使用多個位元組的儲存空間。這在具有複雜或非拉丁文字的語言中很常見,例如日語或中文。 PHP 中有幾個多位元組函數,如 mb_strlen()、mb_substr()、mb_strtolower()、mb_strpos() 等。但也有一些函數,如 trim()、ltrim()、rtrim()、ucfirst()、lcfirst () 等缺乏直接的多位元組等價物。

感謝 PHP 8.4,其中將會加入新的多位元組函數。它們包括:mb_trim()、mb_ltrim()、mb_rtrim()、mb_ucfirst() 和 mb_lcfirst()。這些函數遵循原始函數簽名,並帶有附加的 $encoding 參數。
讓我們討論一下新的 mb_functions:

  1. mb_trim():

    刪除多位元組字串開頭和結尾的所有空白字元。

    函數簽章:

      function mb_trim(string $string, string $characters = " \f\n\r\t\v\x00\u{00A0}\u{1680}\u{2000}\u{2001}\u{2002}\u{2003}\u{2004}\u{2005}\u{2006}\u{2007}\u{2008}\u{2009}\u{200A}\u{2028}\u{2029}\u{202F}\u{205F}\u{3000}\u{0085}\u{180E}", ?string $encoding = null): string {}
    
    登入後複製

    參數:

    • $string:要修剪的字串。
    • $characters:可選參數,包含要修剪的字元清單。
    • $encoding:encoding參數指定用於解釋字串的字元編碼,確保多位元組字元被正確處理。常見的編碼包括UTF-8。
  2. mb_ltrim():

    刪除多位元組字串開頭的所有空白字元。

    函數簽章:

      function mb_ltrim(string $string, string $characters = " \f\n\r\t\v\x00\u{00A0}\u{1680}\u{2000}\u{2001}\u{2002}\u{2003}\u{2004}\u{2005}\u{2006}\u{2007}\u{2008}\u{2009}\u{200A}\u{2028}\u{2029}\u{202F}\u{205F}\u{3000}\u{0085}\u{180E}", ?string $encoding = null): string {}
    
    登入後複製
  3. mb_rtrim():

    刪除多位元組字串末尾的所有空白字元。

    函數簽章:

      function mb_rtrim(string $string, string $characters = " \f\n\r\t\v\x00\u{00A0}\u{1680}\u{2000}\u{2001}\u{2002}\u{2003}\u{2004}\u{2005}\u{2006}\u{2007}\u{2008}\u{2009}\u{200A}\u{2028}\u{2029}\u{202F}\u{205F}\u{3000}\u{0085}\u{180E}", ?string $encoding = null): string {}
    
    登入後複製
  4. mb_ucfirst():

    將給定多位元組字串的第一個字元轉換為標題大小寫,其餘字元保持不變。

    函數簽章:

      function mb_ucfirst(string $string, ?string $encoding = null): string {}
    
    登入後複製
  5. mb_lcfirst():

    與 mb_ucfirst() 類似,但它將給定多位元組字串的第一個字元轉換為小寫。

    函數簽章:

      function mb_lcfirst(string $string, ?string $encoding = null): string {}
    
    登入後複製

結論

我希望這篇部落格能讓您對 PHP 8.4 中即將發生的一些變化有一個很好的概述。新版本似乎引入了令人興奮的更新,這將增強開發人員的體驗。一旦正式發布我就迫不及待地開始使用它。
如需了解更多資訊和更新,請造訪官方 RFC 頁面。

以上是PHP - 發現最新最好的的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!