この例では、まず基底クラスおよびそのクラスの派生クラスを定義します。 基底クラスは食用かどうか、色とかいった、一般的な野菜を記述します。 サブクラス 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";
// 変数 veggie のプロパティを表示
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 は Vegetable のサブクラスであるクラス Spinach のインスタンスです。
