LoginSignup
94
82

More than 5 years have passed since last update.

【PHP】タイプヒンティング

Last updated at Posted at 2015-03-11

これ何?

パラメータの型を指定できる。

指定できる型は、オブジェクト、インターフェイス、配列、callable(PHP5.4以降)。クラスや、インターフェイスを指定した場合、その子クラスや実装クラスも利用できる。

スカラー型(intやstringやbool)は使えない。

具体例

1.array

array以外を渡すとエラー。

function type_test(array $array){   
}

//タイプヒントがarrayなのに、パラメータがint型なのでエラー。
type_test(1);
//=>Catchable fatal error:Argument 1 passed to type_test() must be of the type array, integer given

2.オブジェクト

タイプヒントとパラメータのクラスの型が違うとエラー。

Class MyClass{
}

Class OtherClass{
}

function type_test(MyClass $class){
}

//タイプヒントがMyClassなのでこれはOK
type_test(new MyClass);

//タイプヒントとパラメータのクラスの型が違うのでエラー
type_test(new OtherClass);
//=>Catchable fatal error: Argument 1 passed to type_test() must be an instance of MyClass, instance of OtherClass given,

タイプヒントが親クラス、パラメータが子クラスでもでもOK。

Class MyClass{
}

Class ChildOfMyClass extends MyClass{
}

function type_test(MyClass $class){
}

//OK
type_test(new ChildOfMyClass);

3.インターフェイス

タイプヒントとパラメータのインターフェイス先の型が違うとエラー。

interface MyInterface{
}

Class MyClass implements MyInterface{
}

Class OtherClass{
}

function type_test(MyInterface $class){
}

//これはOK
type_test(new MyClass);

//タイプヒントとパラメータのインターフェイス先の型が違うのでエラー
type_test(new OtherClass);
//=>Catchable fatal error: Argument 1 passed to type_test() must implement interface MyInterface, instance of OtherClass given,

4.callable

少しわかりづらいけど、コールバック可能な、つまり、存在する関数でないとエラーになる。

function func(){
}

function type_test(callable $func){
}

//存在する関数なのでOK
type_test('func');

//存在しない関数なのでエラー。
type_test('not_exists_func');
//=>Catchable fatal error: Argument 1 passed to type_test() must be callable, string given

メリットは?

  • パラメータに何を渡したら良いかすぐにわかるので可読性が上がる。
  • パラメータの型が保障される。パラメータの型が違うことが原因の不具合はすぐに検出できる。簡易的なパラメータチェック。
94
82
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
94
82