PHP Late Static Bindings
PHP/매뉴얼 번역 2008/06/20 00:43
PHP 5.3.0 이후 PHP 는 Late Static Bindings 라는 기능을 도입하였다. 이 기능을 사용하면 정적 상속컨텍스트에서 호출된 클래스를 참조할 수 있다.
이 Late Static Bindings 라는 이름은 내부동작을 고려하여 붙여진 이름이다. Late Bindings 의 유래는 메소드를 정의하고 있는 클래스를 사용해도 static:: 의 해결이 불가능해졌기때문이다. 그 대신 실행시 정보를 기본으로 해결할수 있게되었다. static binding" 의 유래는 정적메소드의 호출에 사용할 수 있게되어서 있다. (단 정적메소드 이외에서도 사용할 수 있다. )
self:: 또는 __CLASS__ 에 의해 현재의 클래스에의 정적참조는 해당 메소드가 속한 클래스에 의해 해결된다.(즉 해당 메소드가 정의된 클래스)
self:: 사용예
class A {
public static function who() {
echo __CLASS__;
}
public static function test() {
self::who();
}
}
class B extends A {
public static function who() {
echo __CLASS__;
}
}
B::test();
?>
출력결과
Late Static Bindings은 이러한 제한을 해결하기위한 키워드를 도입해서 실행시 맨처음에 호출된 클래스를 참조하도록 하고 있다. 이 키워드를 사용하면 앞에서 예를 든 test() 에서 B 를 참조할수 있게된다. 이 키워드는 새롭게 추가한 것이 아니고 이미 예약된 static 를 사용하고 있다.
static:: 의 간단한 사용법
class A {
public static function who() {
echo __CLASS__;
}
public static function test() {
static::who(); // Here comes Late Static Bindings
}
}
class B extends A {
public static function who() {
echo __CLASS__;
}
}
B::test();
?>
주의: static:: 의 동작은 정적메소드에서는 $this 와 다르다! $this-> 는 상속규칙을 따르지만 static:: 는 따르지 않는다.
비정적 컨텍스에서의 static:: 사용법
<?php
class TestChild extends TestParent {
public function __construct() {
static::who();
}
public function test() {
$o = new TestParent();
}
public static function who() {
echo __CLASS__."\n";
}
}
class TestParent {
public function __construct() {
static::who();
}
public static function who() {
echo __CLASS__."\n";
}
}
$o = new TestChild;
$o->test();
?> 결과
TestParent
주의: 정적호출이 대체없이 완전하게 해결된 시점에서 종료한다.
class A {
public static function foo() {
static::who();
}
public static function who() {
echo __CLASS__."\n";
}
}
class B extends A {
public static function test() {
A::foo();
}
public static function who() {
echo __CLASS__."\n";
}
}
B::test();
?>
결과
특수한경우
PHP 에서 메소드를 호출하는 방법엔 여러가지가 있다. 예를 들어 콜백 , 매직메소드등이 그중에 하나이다. Late Static Bindings 은 실행시의 정보를 바탕으로 해결을 하며 , 이런 특수한 경우에는 예상치못한 결과를 낼 수 도 있다.
매직메소드내에서의Late Static Bindings
class A {
protected static function who() {
echo __CLASS__."\n";
}
public function __get($var) {
return static::who();
}
}
class B extends A {
protected static function who() {
echo __CLASS__."\n";
}
}
$b = new B;
$b->foo;
?>
결과
원문링크:http://www.php.net/manual/en/language.oop5.late-static-bindings.php
목차로
PHP 클래스와 오브젝트 ( Classes and Objects ) PHP 5
'PHP > 매뉴얼 번역' 카테고리의 다른 글
| PHP 세션 - 기정의 정수 (0) | 2008/06/25 |
|---|---|
| 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 |