在這個(gè)例子中,我們首先定義了一個(gè)基類(lèi)和該類(lèi)的擴(kuò)展。 這個(gè)基類(lèi)描述了普通的蔬菜,關(guān)于它是否可食用及其顏色。 子類(lèi) Spinach 添加了烹飪的方法和另一個(gè)檢查是否已烹飪的方法。
示例 #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
?>
接下來(lái)我們從這些類(lèi)中實(shí)例化了兩個(gè)對(duì)象,并打印了他們的信息,包括了他們類(lèi)的繼承關(guān)系。 同時(shí)我們也定了一些實(shí)用函數(shù),主要為了漂亮地打印出這些變量。