PHP 5 에서 타입 힌트를 도입했습니다. 함수는 이제 파라미터를 객체(함수 프로토 타입에 클래스의 이름을 명시하는것으로), 인터페이스, 배열(PHP 5.1 이후) 또는 callable(PHP 5.4 이후) 로 강제할수 있게 되었습니다. 하지만, NULL 을 디폴트 값으로 지정하게 되면, 이후 호출시 NULL을 인자로 넘기는것도 가능합니다.
클래스나 인터페이스가 타입힌트로 사용되면 그의 모든 자식이나 구현체들은 인자로 넘기는게 가능합니다.
타입 힌트는 int 또는 string 과 같은 스칼라 타입은 사용될수 없습니다. 리소스 와 트레이트 또한 사용될 수 없습니다.
Example #1 타입 힌트 예제
<?php
// An example class
class MyClass
{
/**
* A test function
*
* 첫번째 파라미터는 OtherClass 타입의 객체여야 함.
*/
public function test(OtherClass $otherclass) {
echo $otherclass->var;
}
/**
* Another test function
*
* 첫번재 파라미터는 배열 이어야 함.
*/
public function test_array(array $input_array) {
print_r($input_array);
}
/**
* 첫번째 파라미터는 iterator 이어야 함.
*/
public function test_interface(Traversable $iterator) {
echo get_class($iterator);
}
/**
* 첫번째 파라미터는 callable 이어야 함.
*/
public function test_callable(callable $callback, $data) {
call_user_func($callback, $data);
}
}
// Another example class
class OtherClass {
public $var = 'Hello World';
}
?>
타입 힌트를 충족하지 않을시 fatal error 결과.
<?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');
// Works: Prints the array
$myclass->test_array(array('a', 'b', 'c'));
// Works: Prints ArrayObject
$myclass->test_interface(new ArrayObject(array()));
// Works: Prints int(1)
$myclass->test_callable('var_dump', 1);
?>
타입힌트는 함수에서도 동작합니다:
<?php
// An example class
class MyClass {
public $var = 'Hello World';
}
/**
* A test function
*
* First parameter must be an object of type MyClass
*/
function myFunction(MyClass $foo) {
echo $foo->var;
}
// Works
$myclass = new MyClass;
myFunction($myclass);
?>
타입힌트에 NULL을 지정할 수 있습니다:
<?php
/* NULL 값 허용 */
function test(stdClass $obj = NULL) {
}
test(NULL);
test(new stdClass);
?>