예제

이 예제에서, 먼저 기반 클래스를 정의하고 그 클래스를 확장합니다. 기반 클래스는 일반 야채를 묘사하고, 식용 여부와 색을 가집니다. 서브클래스 Spinach는 요리하는 메쏘드와 요리되었는지 확인하는 메쏘드를 추가합니다.

Example #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;
   }
   
// 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;
   }
   
// Spinach 클래스 끝

?>

이제 이 클래스로부터 두 객체 인스턴스를 만들고, 클래스 상속을 포함한 정보를 출력합니다. 변수를 깔끔하게 출력하기 위한 몇몇 보조 함수도 정의합니다.

Example #2 test_script.php

<pre>
<?php

include "classes.inc";

// 보조 함수

function print_vars($obj
{
foreach (
get_object_vars($obj) as $prop => $val) {
    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
{
if (
is_subclass_of($GLOBALS[$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";
}
}

// 두 객체 인스턴스 생성

$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 객체가 Vegetable의 서브클래스인 Spinach 클래스의 인스턴스라는 점입니다. 그러므로 스크립트의 마지막 부분은 다음을 출력합니다:

   [...]
Parentage:
Object leafy does not belong to a subclass of Spinach
Object leafy belongs to class spinach a subclass of Vegetable

add a note add a note

User Contributed Notes

There are no user contributed notes for this page.
To Top