&reftitle.examples;
In this example, we first define a base class and an extension
of the class. The base class describes a general vegetable,
whether it is edible, and what is its color. The subclass
Spinach adds a method to cook it and another to
find out if it is cooked.
Class Definitions
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;
}
}
?>
]]>
We then instantiate 2 objects from these classes and print out
information about them, including their class parentage.
We also define some utility functions, mainly to have a nice printout
of the variables.
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";
}
}
// instantiate 2 objects
$veggie = new Vegetable(true, "blue");
$leafy = new Spinach();
// print out information about objects
echo "veggie: CLASS " . get_class($veggie) . "\n";
echo "leafy: CLASS " . get_class($leafy);
echo ", PARENT " . get_parent_class($leafy) . "\n";
// show veggie properties
echo "\nveggie: Properties\n";
printProperties($veggie);
// and leafy methods
echo "\nleafy: Methods\n";
printMethods($leafy);
echo "\nParentage:\n";
objectBelongsTo($leafy, Spinach::class);
objectBelongsTo($leafy, Vegetable::class);
?>
]]>
&examples.outputs;
One important thing to note in the example above is that
the object $leafy is an instance of the class
Spinach which is a subclass of
Vegetable.