bunty's blog

ググったこととか勉強したことのメモ

PHP の @ はエラー制御演算子

全然知らなかったけど、エラー制御演算子ってものがあるらしい。 式の前に @ をつけた場合に、エラーメッセージが無視される。

www.php.net

ドキュメント通りのこのコードを実行してみる。 $cache$key もないのでもちろん動かないが何もエラーは表示されない。

<?php declare(strict_types=1);

$value = @$cache[$key];

次にエラー制御演算子を削除して実行してみる。

<?php declare(strict_types=1);

$value = $cache[$key];

warning が出るようになった。

PHP Warning:  Undefined variable $cache in /Users/user/workspace/test.php on line 3

Warning: Undefined variable $cache in /Users/user/workspace/test.php on line 3
PHP Warning:  Undefined variable $key in /Users/user/workspace/test.php on line 3

Warning: Undefined variable $key in /Users/user/workspace/test.php on line 3
PHP Warning:  Trying to access array offset on value of type null in /Users/user/workspace/test.php on line 3

Warning: Trying to access array offset on value of type null in /Users/user/workspace/test.php on line 3

$value は null になっている。

<?php declare(strict_types=1);

$value = @$cache[$key];
var_dump($value); // NULL