タイプヒンティング

PHP 5では、タイプヒンティング(Type Hinting)が導入されました。 これにより、関数は、 (クラスの名前を関数プロトタイプの中に指定することにより) パラメータをオブジェクトもしくは配列 (PHP5.1以降) が必ず指定されるようにすることができるようになりました。

例 19-41. タイプヒンティングの例

<?php
// とあるクラス
class MyClass
{
    
/**
     * テスト関数
     *
     * 第 1 引数は OtherClass 型のオブジェクトでなければならない
     */
    
public function test ( OtherClass $otherclass ) {
        echo
$otherclass -> var ;
    }


    
/**
     * もう一つのテスト関数
     *
     * 第 1 引数は配列でなければならない
     */
    
public function test_array (array $input_array ) {
        
print_r ( $input_array );
    }
}

// もう一つのサンプルクラス
class OtherClass {
    
public $var = 'Hello World' ;
}
?>

タイプヒントの指定を満たさないと致命的なエラーとなります。

<?php
// それぞれのクラスのインスタンス
$myclass = new MyClass ;
$otherclass = new OtherClass ;

// Fatal Error: Argument 1 must be an object of class OtherClass
$myclass -> test ( 'hello' );

// Fatal Error: Argument 1 must be an instance of OtherClass
$foo = new stdClass ;
$myclass -> test ( $foo );

// Fatal Error: Argument 1 must not be null
$myclass -> test ( null );

// Works: Prints Hello World
$myclass -> test ( $otherclass );

// Fatal Error: Argument 1 must be an array
$myclass -> test_array ( 'a string' );

// 動作する: 配列の内容を表示する
$myclass -> test_array (array( 'a' , 'b' , 'c' ));
?>

タイプヒンティングは、関数でも使用できます。

<?php
// とあるクラス
class MyClass {
    
public $var = 'Hello World' ;
}

/**
* テスト関数
*
* 第 1 引数は MyClass 型のオブジェクトでなければならない
*/
function MyFunction ( MyClass $foo ) {
    echo
$foo -> var ;
}

// 動作する
$myclass = new MyClass ;
MyFunction ( $myclass );
?>

タイプヒントは、 object 型や array 型 (PHP5.1以降) でのみ使用できます。 int および string のような 通常の型でのタイプヒンティングはサポートされません。