🪈
パイプ演算子 (Pipe operator) がマージされたので一足先に使ってみる
PHP 8.5 からパイプ演算子が使えるようになるそうです。
先日、master にマージされたので手元でビルドして使ってみました。
書き方
RFC から抜粋。
Pipe (|>) evaluates left to right by passing the value (or expression result) on the left as the first and only parameter to the callable on the right. That is, the following two code fragments are logically equivalent:
パイプ演算子 |>
はの左側の値を右側の callable に渡して評価します。callable の引数は1つである必要があります。
文字列を複数の関数でこねくり回すような場合に嬉しい機能です。
コード
$str = '<div>You should eat fruits, vegetables, and fiber every day.</div>'
|> htmlspecialchars(...)
|> fn($v) => str_replace('fruits', 'pizza', $v)
|> fn($v) => str_replace('vegetables', 'beer', $v)
|> fn($v) => str_replace('fiber', 'ice cream', $v)
;
echo $str;
出力結果
PHP 8.4系
% php pipe-operator.php
PHP Parse error: syntax error, unexpected token ">" in /Users/muraoka/pipe-operator.php on line 4
Parse error: syntax error, unexpected token ">" in /Users/muraoka/pipe-operator.php on line 4
PHP 8.5
% <div>You should eat pizza, beer, and ice cream every day.</div>
Discussion