[PHP]タイプヒンティングに使える型・使えない型

PHPのタイプヒンティング

PHP5では、関数・メソッドのパラメーターの型を指定する、タイプヒンティングが利用できます。
例:

function type_test(array $array) {}
type_test(1);

これを実行すると、「PHP Catchable fatal error: Argument 1 passed to type_test() must be of the type array, integer given」というエラーが表示されます。

array型を想定しているパラメーターにスカラー型(この場合は整数)を与えているからです。

以下、PHPのタイプヒンティングにおいて使える型・使えない型を整理します。なお、前提とするPHPのバージョンは5.4です。

タイプヒンティングに使える型

PHPでタイプヒンティングに使えるのは、「オブジェクトもしくはインターフェイス、配列 (PHP 5.1 以降)、callable (PHP 5.4 以降) 」です(PHPマニュアル – タイプヒンティング)。

「オブジェクト」は任意のクラスのオブジェクトのこと。「インターフェイス」は、任意のインターフェイスを実装したクラスのオブジェクトのことです。
例:

// インターフェイスを定義
interface UserInterface
{
public function ui();
}
// UserInterfaceを実装
class MyUserInterface implements UserInterface
{
public function ui() {}
}
class MyClass
{
// UserInterfaceの実装をパラメーターとして受け取るメソッド
public function test_interface(UserInterface $ui)
{
echo get_class($ui);
}
}
$myui = new MyUserInterface();
$myc = new MyClass();
$myc->test_interface($myui); // MyUserInterface
// $myc->test_interface($myc); // MyClassはUserInterfaceの実装ではないのでFatal Error

配列はそのまんま配列(array型)のことですね。

callableに関しては、ちゃんとした説明の自信はありませんが、以下の例のような動きをします。

class MyClass
{
public function test_callable(callable $callback)
{
call_user_func($callback);
}
}
function test() {
echo 'test() is called';
}
class TestClass
{
public static function test()
{
echo 'TestClass::test is called';
}
}
$mc = new MyClass();
$mc->test_callable('test'); // test() is called
$mc->test_callable(array('TestClass', 'test')); // TestClass::test is called

引数として与えた文字列や配列を元に関数を探し、その関数を呼び出し可能であればcallableということになるようです。

タイプヒンティングに使えない型

まず、スカラー型が使えません。スカラー型とは、論理値(boolean)・整数(integer)・浮動小数点数(float/double)・文字列(string)のことです。

また、任意のトレイトを継承するオブジェクトか否かはタイプヒンティングで指定することはできません。

コメントをどうぞ

コメントを残す