&reftitle.examples;
この例では、まず基底クラスおよびそのクラスの派生クラスを定義します。
基底クラスは食用かどうか、色とかいった、一般的な野菜を記述します。
サブクラス Spinach は、
その野菜の料理法と調理済であるかどうかの情報を追加します。
クラスの定義
Vegetable
edible = $edible;
$this->color = $color;
}
public function isEdible()
{
return $this->edible;
}
public function getColor()
{
return $this->color;
}
}
?>
]]>
Spinach
cooked = true;
}
public function isCooked()
{
return $this->cooked;
}
}
?>
]]>
続いて、これらのクラスから二つのオブジェクトのインスタンスを作成し、
親クラスを含む情報を出力します。
また、いくつかのユーティリティ関数を定義します。これらは主に変数
を格好良く表示するためのものです。
test_script.php
$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);
?>
]]>
&examples.outputs;
注意すべき大事な点ですが、上記の例ではオブジェクト
$leafy は
Vegetable のサブクラスであるクラス
Spinach のインスタンスです。