把標題轉成網址用的 slug,傳統寫法是這樣:
$slug = strtolower(str_replace(' ', '-', preg_replace('/[^a-z0-9 ]/i', '', trim($title))));
閱讀順序和執行順序相反:最先執行的 trim 寫在最裡面。PHP 8.5 新增的管線運算子 |> 讓程式照執行順序寫。
三種寫法比較
$title = ' PHP 8.5 Pipe Operator: Hello World! ';
// 傳統寫法:由內往外讀
$slug1 = strtolower(str_replace(' ', '-', preg_replace('/[^a-z0-9 ]/i', '', trim($title))));
// 傳統寫法:拆成暫存變數
$tmp = trim($title);
$tmp = preg_replace('/[^a-z0-9 ]/i', '', $tmp);
$tmp = str_replace(' ', '-', $tmp);
$slug2 = strtolower($tmp);
// PHP 8.5 管線運算子:由左往右讀
$slug3 = $title
|> trim(...)
|> (fn($s) => preg_replace('/[^a-z0-9 ]/i', '', $s))
|> (fn($s) => str_replace(' ', '-', $s))
|> strtolower(...);
var_dump($slug1, $slug2, $slug3, $slug1 === $slug3);
輸出(PHP 8.5.4):
string(32) "php-85-pipe-operator-hello-world"
string(32) "php-85-pipe-operator-hello-world"
string(32) "php-85-pipe-operator-hello-world"
bool(true)
三種寫法結果相同。$a |> f(...) 等於 f($a),左邊的值成為右邊函式的唯一參數。
右邊可以放什麼
右邊必須是「接受一個參數」的 callable:
echo 'abc' |> strtoupper(...), "\n"; // ABC,第一級 callable 語法
echo 'abc' |> 'strrev', "\n"; // cba,字串形式的函式名稱
$csv = 'a,b,c' |> (fn($s) => explode(',', $s)); // 多參數函式要包一層
$total = [3, 1, 2]
|> (fn($a) => array_map(fn($x) => $x * 10, $a))
|> array_sum(...);
var_dump($total); // int(60)
explode、array_map 這類需要多個參數、而且要處理的資料不在第一個參數的函式,都要用箭頭函式包起來。
陷阱一:箭頭函式一定要加括號
echo "x" |> fn($s) => strtoupper($s) |> strrev(...);
PHP Fatal error: Arrow functions on the right hand side of |> must be parenthesized
這是編譯期錯誤,整個檔案都不會執行。原因是箭頭函式的本體會盡量往右吃,|> strrev(...) 會被當成箭頭函式本體的一部分,PHP 直接禁止這種寫法。
陷阱二:不能傳參考
function f(string &$s) { $s .= "!"; return $s; }
$v = "hi";
echo $v |> f(...);
PHP Fatal error: Uncaught Error: f(): Argument #1 ($s) could not be passed by reference
管線傳的是值,不能交給以參考接收參數的函式。sort()、array_push() 這類直接修改陣列的內建函式也一樣不能用。
什麼時候適合用
- 字串清理、資料轉換這種一步接一步的處理流程。
- 原本要寫三、四層巢狀呼叫,或一連串
$tmp = ...的地方。
不適合的情況:只有一兩步的呼叫,直接寫比較清楚;每一步都要包箭頭函式時,可讀性未必比暫存變數好。
> [!NOTE]
> |> 是 PHP 8.5 的新語法,程式碼裡只要出現,在 8.4 以下就會在解析階段失敗。要支援舊版本的套件,暫時不要使用。
發表留言