LoginSignup
6
6

More than 5 years have passed since last update.

PHP7調査(22)PHP組み込みクラスのコンストラクタでエラーが起きると必ず例外を投げるようになった

Last updated at Posted at 2015-04-22

DateTimeやPDOなど、PHP組み込みのクラスはC言語で実装されています。

このようなクラスのコンストラクタでエラーが発生した際、nullを返すもの、警告を出すもの、致命的エラーになるもの、と実装がバラバラになっていました。これがPHP7で統一され、必ず例外がスローされるようになりました。

PHP5までは、intlエクステンションに含まれるMessageFormatterクラスがコンストラクタエラーでnullを返していました。

<?php
$mf = new MessageFormatter("en_US", "{this was made intentionally incorrect}");
var_dump($mf);
$ php5 /tmp/foo.php
NULL

PHP7では、下記のようにIntlExceptionがスローされるようになりました。

$ php7 /tmp/foo.php
PHP Fatal error:  Uncaught exception 'IntlException' with message 'Constructor failed' in /tmp/foo.php:2
Stack trace:
#0 /tmp/foo.php(2): MessageFormatter->__construct('en_US', '{this was made ...')
#1 {main}
  thrown in /private/tmp/foo.php on line 2

(補足ですが、nullを返すようなクラスは普段使うものの中には無さそうです、さすがに)

注意点1

PHP同梱でないエクステンションの中には、行儀の悪いものが残っているかもしれません。今回のRFCを根拠にバグレポートを送ったり、Pull Requestを投げたりすると良いでしょう。

注意点2

RFCの時点とは返すExceptionが変わっているものもあります。例えば、コンストラクタ引数の型エラーはTypeExceptionに統一されています。

参照

6
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
6