PHP 8.5 最受注意的是管線運算子 |>,另外還有幾個日常馬上用得到的功能。以下都在 PHP 8.5.4 實測。
array_first、array_last
取陣列的第一個、最後一個元素,以前的寫法各有缺點:
$users = ['b' => 'Bob', 'a' => 'Alice', 'c' => 'Carol'];
var_dump(reset($users), end($users)); // 會移動陣列的內部指標
var_dump($users[array_key_first($users)]); // 要寫兩次變數名稱
var_dump(array_first($users), array_last($users));
var_dump(array_first([]));
var_dump(array_first(array_filter([3, 8, 12], fn($n) => $n > 5)));
string(3) "Bob"
string(5) "Carol"
string(3) "Bob"
string(3) "Bob"
string(5) "Carol"
NULL
int(8)
reset() 和 end() 需要傳入變數,不能直接放函式呼叫的結果。array_first() 可以直接接 array_filter() 的結果,空陣列回傳 null。
注意:陣列裡的值本身是 null 時,回傳值也是 null,分不出是空陣列還是第一個值為 null,這時先用 $arr === [] 判斷。
#[\NoDiscard]:提醒別忘了接回傳值
有些函式不修改原本的資料,而是回傳新的結果,呼叫時很容易忘了接:
#[\NoDiscard("回傳值是新的陣列,原陣列不會被修改")]
function withItem(array $items, string $item): array {
return [...$items, $item];
}
$cart = ['book'];
withItem($cart, 'pen'); // 忘了接回傳值
$cart = withItem($cart, 'pen'); // 正確
(void) withItem($cart, 'cup'); // 明確表示不要回傳值
print_r($cart);
PHP Warning: The return value of function withItem() should either be used or intentionally ignored by casting it as (void), 回傳值是新的陣列,原陣列不會被修改 in nodiscard.php on line 8
Array
(
[0] => book
[1] => pen
)
只有忘了接的那一行出現 Warning,括號裡的說明也一起印出來。真的不需要回傳值時,用 (void) 明確表示,就不會有警告。
clone with:複製時順便修改屬性
readonly 物件要「改一個值」,只能複製一份新的。過去要重寫整個構造函式呼叫,PHP 8.5 可以在 clone 時指定要改的屬性:
final readonly class Config {
public function __construct(
public string $host,
public int $port,
public bool $debug = false,
) {}
public function withPort(int $port): static {
return clone($this, ['port' => $port]);
}
}
$a = new Config('localhost', 8080);
$b = $a->withPort(9090);
var_dump($a->port, $b->port); // int(8080) int(9090)
原物件不變,新物件的 port 是 9090。
陷阱是在類別外面直接用:
$c = clone($a, ['debug' => true]);
Error: Cannot modify protected(set) readonly property Config::$debug from global scope
readonly 屬性預設是 protected(set),只有類別自己和子類別能寫入,clone with 也遵守這個規則。所以通常像 withPort() 這樣包成方法,由類別決定哪些屬性可以改。
URI 擴充:取代 parse_url
parse_url() 不遵循任何標準,遇到奇怪的網址會給出奇怪的結果:
var_dump(parse_url('http://example.com:80:80/path'));
array(4) {
["scheme"]=>
string(4) "http"
["host"]=>
string(14) "example.com:80"
["port"]=>
int(80)
["path"]=>
string(5) "/path"
}
host 被解析成 example.com:80。PHP 8.5 內建的 URI 擴充依照標準解析,格式錯誤直接丟出例外:
use Uri\Rfc3986\Uri;
use Uri\WhatWg\Url;
new Uri('http://example.com:80:80/path');
// Uri\InvalidUriException: The specified URI is malformed
$u = new Uri('https://user@example.com:8443/a/b/../c?q=1#top');
var_dump($u->getScheme(), $u->getHost(), $u->getPort(), $u->getPath(), $u->getQuery(), $u->getFragment());
$url = new Url('HTTPS://EXAMPLE.com:443/a/./b/../c');
echo $url->toAsciiString();
string(5) "https"
string(11) "example.com"
int(8443)
string(4) "/a/c"
string(3) "q=1"
string(3) "top"
https://example.com/a/c
兩個類別對應兩個標準:Uri\Rfc3986\Uri 照 RFC 3986,Uri\WhatWg\Url 照瀏覽器使用的 WHATWG URL 標準。後者會把協定和主機轉小寫、去掉預設的 443 埠、處理 . 和 ..,結果和瀏覽器一致。驗證使用者輸入的網址、防止 SSRF 時,用和瀏覽器相同的解析規則比較不會出現落差。
其他小改進
get_error_handler()、get_exception_handler():取得目前設定的處理函式,過去只能透過「設定一個新的再還原」來取得。- Fatal error 加上堆疊追蹤,由
fatal_error_backtraces設定控制,預設開啟:
PHP Fatal error: Allowed memory size of 33554432 bytes exhausted (tried to allocate 2097152 bytes) in fatal_trace.php on line 6
Stack trace:
#0 fatal_trace.php(6): str_repeat()
#1 {main}
以前記憶體不足這類 fatal error 只有一行訊息,現在至少看得到是哪個呼叫觸發的。
發表留言