「fn」というワードはPHP7.4から予約語になったというのを知るに至った経緯として、$ symfony serveでローカルサーバを立てて
$ symfony serve
[OK] Web server listening
The Web server is using PHP FPM 7.3.11
https://127.0.0.1:8000
[Web Server ] Jan 18 18:48:55 |INFO | PHP listening path="/usr/sbin/php-fpm" php="7.3.11" port=61746
ブラウザで表示確認をすると、以下の500エラーがでました😱
(phpenvでいろんなPHPバージョンを使ってます。)
HTTP 500 Internal Server Error syntax error, unexpected 'fn' (T_STRING), expecting :: (T_PAAMAYIM_NEKUDOTAYIM)
ParseError
in /Users/xxx/my-project/vendor/laminas/laminas-code/src/Generator/ClassGenerator.php (line 480)
470 /**
471 * @param string $implementedInterface
472 * @return bool
473 */
474 public function hasImplementedInterface($implementedInterface)
475 {
476 $interfaceType = TypeGenerator::fromTypeString($implementedInterface);
477
478 return (bool) array_filter(
479 array_map([TypeGenerator::class, 'fromTypeString'], $this->implementedInterfaces),
480 static fn (TypeGenerator $interface): bool => $interfaceType->equals($interface)
481 );
482 }
よーく確認してみると、
「symfony php --version と php --versionのバージョンが違う」
ことに気づきました💦
$ symfony php --version
PHP 7.3.11 (cli) (built: Jun 5 2020 23:50:40) ( NTS )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.3.11, Copyright (c) 1998-2018 Zend Technologies
$ php --version
PHP 7.4.9 (cli) (built: Dec 26 2020 23:21:06) ( NTS )
Copyright (c) The PHP Group
Zend Engine v3.4.0, Copyright (c) Zend Technologies
with Zend OPcache v7.4.9, Copyright (c), by Zend Technologies
with Xdebug v3.0.1, Copyright (c) 2002-2020, by Derick Rethans
そこで、$ symfony serve でもPHP 7.4.9で動くように設定します。
参照:https://symfony.com/doc/current/setup/symfony_server.html#different-php-settings-per-project
$ cd my-project/
$ echo 7.4.9 > .php-version
$ symfony php --version # PHP 7.3.11 -> 7.4.9に変更完了
PHP 7.4.9 (cli) (built: Dec 26 2020 23:21:06) ( NTS )
Copyright (c) The PHP Group
Zend Engine v3.4.0, Copyright (c) Zend Technologies
with Zend OPcache v7.4.9, Copyright (c), by Zend Technologies
with Xdebug v3.0.1, Copyright (c) 2002-2020, by Derick Rethans
$ symfony serve # PHP 7.4.9でサーバ立てることに成功
[OK] Web server listening
The Web server is using PHP FPM 7.4.9
https://127.0.0.1:8000
[Web Server ] Jan 18 18:50:59 |INFO | PHP listening path="/Users/xxx/.phpenv/versions/7.4.9/sbin/php-fpm" php="7.4.9" port=62271
お! PHP7.4.9でサーバ立てるようになったみたいです!
と同時にsyntax error, unexpected 'fn' (T_STRING), expecting :: (T_PAAMAYIM_NEKUDOTAYIM)のエラーもなくなりました🎉
めでたし、めでたし👏
syntax error, unexpected ‘fn’ (T_STRING), expecting :: (T_PAAMAYIM_NEKUDOTAYIM)の解明
参照:https://www.php.net/manual/ja/tokens.php
Google翻訳先生に訳してもらうと、
構文エラー、予期しない '楽しい'(t_string)、予期する::( t_pamaim_nikoodatim)
おそらく fn = 楽しい って訳してくれてます💦
ググっていくと、「fn」はPHP7.4から予約語になったらしいです!
というかアロー関数(無名関数)が使えるようになり、その予約語としてfnを使います。
(風の噂でアロー関数が使えるようになったというのは知っていたのですが書き方まで知らなかったです😅)
アロー関数は
fn (argument_list) => exprという形で記述します。
よって、PHP 7.4まではアロー関数がなかったために以下の該当箇所を、「::」を使うスコープ定義演算子 (::)のことではないですか?と教えてくれたのかもしれません。
static fn (TypeGenerator $interface): bool => $interfaceType->equals($interface)