範例
在這個例子中,首先定義了一個基類和該類的擴充套件。基類描述了普通的蔬菜, 是否可食用及其顏色。子類 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;
}
}
?>
Spinach
<?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
// 註冊自動載入器以載入類
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";
}
}
// 實例化 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";
printProperties($veggie);
// 和 leafy 的方法
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 的實例(Vegetable 的子類)。