在此範例中,我們首先定義一個基底類別和該類別的延伸。基底類別描述了一般的蔬菜,無論它是否可食用,以及它的顏色。子類別 Spinach(菠菜) 添加了一個烹飪它的方法和另一個用於判斷它是否已煮熟的方法。
範例 #1 類別定義
Vegetable(蔬菜)
<?php
class Vegetable {
public $edible;
public $color;
public function __construct($edible, $color = "green")
{
$this->edible = $edible;
$this->color = $color;
}
public function isEdible()
{
return $this->edible;
}
public function getColor()
{
return $this->color;
}
}
?>
菠菜
<?php
class Spinach extends Vegetable {
public $cooked = false;
public function __construct()
{
parent::__construct(true, "green");
}
public function cook()
{
$this->cooked = true;
}
public function isCooked()
{
return $this->cooked;
}
}
?>
接著,我們會從這些類別實例化兩個物件,並印出關於它們的資訊,包括它們的類別繼承關係。我們也定義了一些工具函式,主要是為了更好地印出變數。
範例 #2 test_script.php
<?php
// register autoloader to load classes
spl_autoload_register();
function printProperties($obj)
{
foreach (get_object_vars($obj) as $prop => $val) {
echo "\t$prop = $val\n";
}
}
function printMethods($obj)
{
$arr = get_class_methods(get_class($obj));
foreach ($arr as $method) {
echo "\tfunction $method()\n";
}
}
function objectBelongsTo($obj, $class)
{
if (is_subclass_of($obj, $class)) {
echo "Object belongs to class " . get_class($obj);
echo ", a subclass of $class\n";
} else {
echo "Object does not belong to a subclass of $class\n";
}
}
// instantiate 2 objects
$veggie = new Vegetable(true, "blue");
$leafy = new Spinach();
// print out information about objects
echo "veggie: CLASS " . get_class($veggie) . "\n";
echo "leafy: CLASS " . get_class($leafy);
echo ", PARENT " . get_parent_class($leafy) . "\n";
// show veggie properties
echo "\nveggie: Properties\n";
printProperties($veggie);
// and leafy methods
echo "\nleafy: Methods\n";
printMethods($leafy);
echo "\nParentage:\n";
objectBelongsTo($leafy, Spinach::class);
objectBelongsTo($leafy, Vegetable::class);
?>
以上範例將會輸出
veggie: CLASS Vegetable leafy: CLASS Spinach, PARENT Vegetable veggie: Properties edible = 1 color = blue leafy: Methods function __construct() function cook() function isCooked() function isEdible() function getColor() Parentage: Object does not belong to a subclass of Spinach Object belongs to class Spinach, a subclass of Vegetable
在上面的例子中,需要注意的一件重要事情是,物件 $leafy 是 Spinach 類別的一個實例,而 Spinach 是 Vegetable 的子類別。