在這個例子中,我們首先定義了一個基類和該類的擴(kuò)展。 這個基類描述了普通的蔬菜,關(guān)于它是否可食用及其顏色。 子類 Spinach 添加了烹飪的方法和另一個檢查是否已烹飪的方法。
示例 #1 classes.inc
<?php
// base class with member properties and methods
class Vegetable {
var $edible;
var $color;
function __construct($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
// extends the base class
class Spinach extends Vegetable {
var $cooked = false;
function __construct()
{
parent::__construct(true, "green");
}
function cook_it()
{
$this->cooked = true;
}
function is_cooked()
{
return $this->cooked;
}
} // end of class Spinach
?>
接下來我們從這些類中實(shí)例化了兩個對象,并打印了他們的信息,包括了他們類的繼承關(guān)系。 同時我們也定了一些實(shí)用函數(shù),主要為了漂亮地打印出這些變量。
示例 #2 test_script.php
<pre>
<?php
include "classes.inc";
// 實(shí)用函數(shù)
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($GLOBALS[$obj]);
echo " a subclass of $class\n";
} else {
echo "Object $obj does not belong to a subclass of $class\n";
}
}
// 實(shí)例化 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";
// 顯示蔬菜的屬性
echo "\nveggie: Properties\n";
print_vars($veggie);
// and leafy methods
echo "\nleafy: Methods\n";
print_methods($leafy);
echo "\nParentage:\n";
class_parentage("leafy", "Spinach");
class_parentage("leafy", "Vegetable");
?>
</pre>
一個重要的東西是注意在上面的例子中,對象 $leafy 是 Spinach 的實(shí)例(Vegetable 的子類),另外腳本的最后部分會輸出以下信息:
[...] Parentage: Object leafy does not belong to a subclass of Spinach Object leafy belongs to class spinach, a subclass of Vegetable