|
|
IX. 클래스/객체 함수소개
이 함수들은 클래스와 객체에 대한 정보를 얻을수 있게 해준다.
특정 객체가 속한 클래스명은 물론 그 객체의 멤버 속성과 메소드를
찾을수 있다. 이 함수들을 사용함으로써, 특정 객체의 클래스 멤버들
뿐만 아니라, 그 객체의 혈통(즉, 그 객체 클래스가 상속하는 클래스)
도 알아낼수 있다.
요구 사항이 확장 모듈을 빌드할 때 외부 라이브러리가 필요하지 않습니다. 설치이 함수들은 설치하지 않아도 사용할 수 있습니다;
PHP 코어의 일부입니다. 런타임 설정이 확장 모듈은 php.ini 설정이 존재하지 않습니다. 리소스 종류이 확장 모듈은 리소스형을 정의하지 않습니다. 상수 정의이 확장 모듈은 상수를 정의하지 않습니다. 예제
다음 예제코드를 보면, 먼저 기본 클래스를 선언하고, 그 클래스를
상속받는 클래스를 선언한다. 기본 클래스는 일반적인 야채에 대한
클래스로, 야채가 먹을수 있는지 아닌지 그리고 그 야채의 색깔이
무엇인지를 정의한다. 하위클래스 Spinach 는
그 야채를 요리하는 메소드와 요리되었는지 알아낼수 있는 메소드를
추가한다.
예 1. classes.inc
<?php
// 멤버 속성과 메소드를 갖는 기본 클래스 class Vegetable {
var $edible; var $color;
function Vegetable( $edible, $color="green" ) { $this->edible = $edible; $this->color = $color; }
function is_edible() { return $this->edible; }
function what_color() { return $this->color; } } // end of class Vegetable
// 기본 클래스를 확장 class Spinach extends Vegetable {
var $cooked = false;
function Spinach() { $this->Vegetable( true, "green" ); }
function cook_it() { $this->cooked = true; }
function is_cooked() { return $this->cooked; } } // end of class Spinach
?>
|
|
이 클래스들로부터 2개의 객체를 생성하고, 그 클래스들의 혈통을
포함한 클래스들의 정보를 출력한다. 또한 변수의 깔끔한 출력을 위한
몇개의 유용한 함수들도 선언한다.
예 2. test_script.php
<pre> <?php
include "classes.inc";
// 유용한 함수들
function print_vars($obj) { $arr = get_object_vars($obj); while (list($prop, $val) = each($arr)) echo "\t$prop = $val\n"; }
function print_methods($obj) { $arr = get_class_methods(get_class($obj)); foreach ($arr as $method) echo "\tfunction $method()\n"; }
function class_parentage($obj, $class) { global $$obj; if (is_subclass_of($$obj, $class)) { echo "Object $obj belongs to class ".get_class($$obj); echo " a subclass of $class\n"; } else { echo "Object $obj does not belong to a subclass of $class\n"; } }
// 2개의 객체 생성
$veggie = new Vegetable(true,"blue"); $leafy = new Spinach();
// 객체 정보를 출력 echo "veggie: CLASS ".get_class($veggie)."\n"; echo "leafy: CLASS ".get_class($leafy); echo ", PARENT ".get_parent_class($leafy)."\n";
// veggie 속성을 보임 echo "\nveggie: Properties\n"; print_vars($veggie);
// leafy 메소드를 보임 echo "\nleafy: Methods\n"; print_methods($leafy);
echo "\nParentage:\n"; class_parentage("leafy", "Spinach"); class_parentage("leafy", "Vegetable"); ?> </pre>
|
위 예제코드에서 가장 유의 해야 할 사항은 객체
$leafy 가 클래스 Spinach
의 인스턴스이고, 이 클래스는 Vegetable 의
하위 클래스라는 것이다. 따라서 위 스크립트의 제일 아래 부분에서는
다음과 같이 출력될것이다:
[...]
Parentage:
Object leafy does not belong to a subclass of Spinach
Object leafy belongs to class spinach a subclass of Vegetable |
|
|