2023 年您應該了解的 20 個 PHP 功能
PHP 總是在不斷發(fā)展,了解最新的功能和改進非常重要。本文介紹了 2023 年您應該了解的 20 個 PHP 功能,每個功能都配有方便的代碼示例。
1. str_contains():
檢查一個字符串是否包含在另一個字符串中。
$sentence = "The quick brown ?? jumps over the lazy ??.";
$word = "??";
if (str_contains($sentence, $word)) {
echo "The sentence contains the word ??.";
}
2. str_starts_with():
檢查字符串是否以給定子字符串開頭。
$sentence = "?? Launching into space!";
if (str_starts_with($sentence, "??")) {
echo "The sentence starts with a rocket emoji!";
}
3. str_ends_with():
檢查字符串是否以給定子字符串結尾。
$sentence = "It's a beautiful day! ??";
if (str_ends_with($sentence, "??")) {
echo "The sentence ends with a sun emoji!";
}
4. get_debug_type():
獲取變量的類型。
$num = 42;
echo get_debug_type($num); // "integer"
5. 獲取資源id():
返回給定資源的唯一標識符。
$file = fopen('test.txt', 'r');
echo get_resource_id($file); // e.g., "7"
6. fdiv():
除法功能,包括支持除以零。
$result = fdiv(10, 0); // INF
7. preg_last_error_msg():
返回最后一個 PCRE 正則表達式執(zhí)行錯誤的人類可讀消息。
preg_match('/(/', '');
echo preg_last_error_msg(); // "missing )"
8. array_key_first():
獲取數(shù)組的第一個鍵。
$array = ['??'=>'Apple', '??'=>'Orange', '??'=>'Grape'];
echo array_key_first($array); // "??"
9. array_key_last():
獲取數(shù)組的最后一個鍵。
$array = ['??'=>'Apple', '??'=>'Orange', '??'=>'Grape'];
echo array_key_last($array); // "??"
10.ErrorException::getSeverity():
獲取錯誤的嚴重性。
try {
trigger_error("Custom error", E_USER_WARNING);
} catch (ErrorException $e) {
echo $e->getSeverity(); // 512
}
11. Filter Functions:
PHP 8 引入了幾個新的filter函數(shù)。下面是使用 filter_var 和 FILTER_VALIDATE_BOOL 的示例:
var_dump(filter_var('yes', FILTER_VALIDATE_BOOL)); // bool(true)
12. Weak Map:
一個保存對象引用的新類,它不會阻止這些對象被垃圾收集。
$weakmap = new WeakMap();
$obj = new stdClass();
$weakmap[$obj] = 'Hello, world!';
13. Value Objects:
PHP 8 引入了構造函數(shù)屬性提升,這是一種用于構造值對象的新語法。
class Money {
public function __construct(
public int $amount,
public string $currency
) {}
}
$tenDollars = new Money(10, 'USD');
14. Match Expression:
這是一個類似 switch 的語句。
echo match (1) {
0 => '??',
1 => '?',
default => '??',
};
15. Nullsafe Operator:
這個新運算符 (?->) 允許在訪問屬性或方法時進行 null 檢查。
class User {
public function getAddress(): ?Address {
// returns Address or null
}
}
$user = new User();
$country = $user?->getAddress()?->country; // no error if getAddress() returns null
16. Named Arguments:
此功能允許您通過指定值名稱將值傳遞給函數(shù)。
new Money(amount: 10, currency: 'USD');
17. Attributes:
在其他編程語言中也稱為注釋。
#[Attribute]
class ExampleAttribute {}
#[ExampleAttribute]
class ExampleClass {}
18. Constructor Property Promotion:
此功能允許將類屬性和構造函數(shù)組合到單個聲明中。
class Money {
public function __construct(
public int $amount,
public string $currency
) {}
}
19. Union Types:
此功能允許類型聲明可以是多種類型之一。
function print_id(int|string $id): void {
echo 'ID: ' . $id;
}
20. 及時編譯(JIT):
PHP 8 引入了兩個 JIT 編譯引擎:Tracing JIT 和 Function JIT。
注意:JIT 編譯不是一個可以直接用代碼片段演示的功能,但它是 PHP 8 中的一項重要改進,可以提供顯著的性能改進。
總結
PHP 是一種在不斷發(fā)展的語言,具有許多令人興奮的新功能和改進。無論您是經(jīng)驗豐富的 PHP 開發(fā)人員還是新手,都值得花時間了解這些新功能并在代碼中使用它們。
保持好奇心,不斷學習,祝你學習愉快!