PHP 타이프 힌팅
PHP/매뉴얼 번역 2008/06/20 00:43PHP 5 에서는 타이프힌팅 (Type Hinting) 이 도입되었다. 함수는 (클래스의 이름을 함수 프로토타이프에서 지정하여) 패러미터를 오브젝트 또는 배열(PHP5.1 이후) 가 반드시 지정되도록 할 수 있게 되었다. 그러나 디폴트 파라미터 값으로 NULL 을 사용한 경우에는 나중에 임의의 값을 파라미터로 지정할 수 있게 되었다.
예
// An example class
class MyClass
{
/**
* A test function
*
* First parameter must be an object of type OtherClass
*/
public function test(OtherClass $otherclass) {
echo $otherclass->var;
}
/**
* Another test function
*
* First parameter must be an array
*/
public function test_array(array $input_array) {
print_r($input_array);
}
}
// Another example class
class OtherClass {
public $var = 'Hello World';
}
?>
타이프힌트의 지정조건을 만족시키지 못하면 캐치가능한 치명적 에러가 발생한다.
<?php
// An instance of each class
$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'));
?> 타이프힌팅은 함수에서도 사용가능하다.
// 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 값을 사용할 수 있다.
/* Accepting NULL value */
function test(stdClass $obj = NULL) {
}
test(NULL);
test(new stdClass);
?>
타이프힌트는 object 타입 , array 타입 (PHP5.1 이후) 에서만 사용할 수 있다. int 및 string 같은 일반적인 타이프힌팅은 지원하지않는다.
원문링크 : http://www.php.net/manual/en/language.oop5.typehinting.php
목차에
PHP 클래스와 오브젝트 ( Classes and Objects ) PHP 5
'PHP > 매뉴얼 번역' 카테고리의 다른 글
| PHP 세션 - 인스톨 / 설정 (0) | 2008/06/25 |
|---|---|
| PHP 세션 - 소개 (0) | 2008/06/25 |
| PHP 세션 (0) | 2008/06/25 |
| PHP 문자열 지정방법 ( Heredoc ) (0) | 2008/06/20 |
| PHP Late Static Bindings (0) | 2008/06/20 |
| PHP 타이프 힌팅 (0) | 2008/06/20 |
| PHP 오브젝트의 비교 (0) | 2008/06/20 |
| PHP 오브젝트의 클론 생성 (0) | 2008/06/20 |
| PHP final 키워드 (0) | 2008/06/20 |
| PHP 매직메소스 (0) | 2008/06/20 |
| PHP 패턴 (0) | 2008/06/20 |