[PHP5.3.0] Late Static Bindings

같은 클래스 안에 속한 정적 함수를 호출 할 때에는 $this 변수를 사용하지 않고 self 키워드를 사용합니다. 이  self 키워드의 특징은 self 를 실행하는 자기 클래스가 아니라 호출하려는 메소드가 정의된 클래스를 의미합니다.

  1: <?php
  2: class ParentClass {
  3:   public static function who() {
  4:     echo 'I am Parent Class.';
  5:   }
  6:
  7:   public static function whoAreYou() {
  8:     self::who();
  9:   }
 10: }
 11:
 12: class ChildClass extends ParentClass {
 13:   public static function who() {
 14:     echo ' I am Child Class.';
 15:   }
 16: }
 17:
 18: ChildClass::whoAreYou();
 19:
 20: ?>

위 코드와 같이 ChildClass 가 ParentClass 를 상속 받았습니다. ChildClass 에 있는 whoAreYour() 함수를 호출하여 who() 함수를 실행했을 때 어떤 문자열이 출력될까요.

결과는 I am Parent Class. 입니다.

정적 함수의 상속 관계를 그림으로 보면 아래와 같습니다.

2009-07-15_135134

Last Static Bindings

PHP 5.3.0 에서 추가된 Late Static Bindings는 static 키워드를 추가하여 정의된 부모 클래스가 아니라 상속을 받은 자기 자신을 지징할 수 있도록 했습니다. 코드를 보면 아래와 같습니다.

  1: <?php
  2: class ParentClass {
  3:   public static function who() {
  4:     echo 'I am Parent Class.';
  5:   }
  6:
  7:   public static function whoAreYou() {
  8:     static::who();
  9:   }
 10: }
 11:
 12: class ChildClass extends ParentClass {
 13:   public static function who() {
 14:     echo ' I am Child Class.';
 15:   }
 16: }
 17:
 18: ChildClass::whoAreYou();
 19:
 20: ?>

바뀐 부분을 눈치 채셨나요? ParentClass 의 whoAreYou() 함수 안에서 self::who() 코드가  static::who() 로 바뀌었습니다. 이렇게 static 키워드를 사용하면 상속 받은 자식 클래스에서 자신의 함수를 사용할 수 있습니다. 이 static 키워드를 사용하면 아래 코드처럼 작성할 수도 있습니다.

아래 코드에서는 ParentClass 에 who() 함수가 없습니다. 그럼에도 불구하고 ParentClass 에서 who() 를 호출하고 있습니다. 이런 경우 ChildClass 의 who() 가 호출 될 것이므로 ParentClass 에 who() 함수가 정의되어 있지 않아도 됩니다.

  1: <?php
  2: class ParentClass {
  3:
  4:   public static function whoAreYou() {
  5:     static::who();
  6:   }
  7: }
  8:
  9: class ChildClass extends ParentClass {
 10:   public static function who() {
 11:     echo ' I am Child Class.';
 12:   }
 13: }
 14:
 15: ChildClass::whoAreYou();
 16:
 17: ?>

About the Author

has written 47 stories on this site.

Copyright © 2012 PHPK.org. All rights reserved.
Theme by Fitobochka and ComFi.com Phone Cards Company.