<?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 的子类)。