LoginSignup
22
21

More than 5 years have passed since last update.

strict 拡張モジュールを導入してスカラー型のタイプヒントを利用する

Last updated at Posted at 2014-11-18

PHP 5.6 で標準モジュールとして導入された phpdbg の作者である Joe Watkins さんが strict 拡張モジュールを公開しました。くわしい経緯に関しては Joe さんのブログ記事をご参照ください。このモジュールを導入すると、次のスカラー型のタイプヒントが利用できるようになります。

  • string
  • integer, int
  • float, double
  • boolean, bool
  • resource

まだ正式バージョンはリリースされていないので、モジュールの利用は学習や評価を目的としたローカル環境にとどめておいたほうがよいでしょう。

インストール

strict モジュールをインストールするには次のコマンドを実行します。

pecl install strict-beta

Windows 版は準備中とのことです。パッケージ情報のページによると 0.2.0 では PHP 5.4.0 とそれ以降のバージョンを対象としてます。

php.ini もしくは スキャンの対象となるディレクトリの ini ファイルに次のコードを追加します。

extension=strict.so

ini ファイルのパスを調べるには次のコマンドを実行します。

php --ini

モジュールが読み込まれるかどうかを調べるには次のコマンドを使います。

php -m

試してみよう

string

ユーザー関数を定義して、string 型のタイプヒントを試してみましょう。

var_dump(
    foo('bar'),
    foo(10)
);

function foo(string $str) {
    return $str;
}

実行すれば、次のエラーメッセージが表示されます。

PHP Catchable fatal error:  Argument 1 passed to foo must be string, integer given in /Users/masakielastic/test/test.php on line 8

Catchable fatal error: Argument 1 passed to foo must be string, integer given in /Users/masakielastic/test/test.php on line 8

boolean、bool

0、0.0、"0"、null、[]、など empty 関数が false と判定する「falsy value」(false っぽい値)をユーザー関数の引数に渡すとエラーになることを確認してみましょう。

function accept_bool(bool $bool) {}
accept_bool(null);

resource

cURL ハンドルを受け取り、それ以外のリソースが来たときはエラーにしてみましょう。

function accept_curl_resource(resource $ch) {

    if ("curl" !== get_resource_type($ch)) {
        exit("$ch is not curl handle.\n");
    }

}

$ch = curl_init();

$file = "test.txt";
touch($file);
$handle = fopen($file, "r");

accept_curl_resource($ch);
accept_curl_resource($handle);

制限事項

このモジュールの制限事項はデフォルトの値に null しか指定できないことです。Joe さんのブログ記事によれば、対策を考え中とのことです。

var_dump(
    foo()
);

function foo(string $str = null) {

    if ($str === null) {
        return 'bar';
    }

    return $str;
}

今後の対応

今後、追加する予定の機能として、PHP 7 に向けて提案されている安全な型変換関数 (RFC: Safe Casting Functions) が挙げられています。この RFC が通った場合、PHP 5 系でも利用できるようにし、RFC が通らなければ strict_cast という名前の関数を導入するとのことです。また、戻り値の型宣言 (RFC: Return Type Declarations) の RFC が通った場合にも対応するとのことです。

22
21
2

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
22
21