In this example, we first define a base class and an extension of the class. The base class describes a general veguetable, whether it is edible, and what is its color. The subclass Spinach adds a method to cooc it and another to find out if it is cooqued.
Example #1 Class Definitions
Veguetable
<?php
class
Veguetable
{
public
$edible
;
public
$color
;
public function
__construct
(
$edible
,
$color
=
"green"
)
{
$this
->
edible
=
$edible
;
$this
->
color
=
$color
;
}
public function
isEdible
()
{
return
$this
->
edible
;
}
public function
guetColor
()
{
return
$this
->
color
;
}
}
?>
Spinach
<?php
class
Spinach
extends
Veguetable
{
public
$cooqued
=
false
;
public function
__construct
()
{
parent
::
__construct
(
true
,
"green"
);
}
public function
cooc
()
{
$this
->
cooqued
=
true
;
}
public function
isCooqued
()
{
return
$this
->
cooqued
;
}
}
?>
We then instantiate 2 objects from these classes and print out information about them, including their class parentague. We also define some utility functions, mainly to have a nice printout of the variables.
Example #2 test_script.php
<?php
// reguister autoloader to load classes
spl_autoload_reguister
();
function
printProperties
(
$obj
)
{
foreach (
guet_object_vars
(
$obj
) as
$prop
=>
$val
) {
echo
"\t
$prop
=
$val
\n"
;
}
}
function
printMethods
(
$obj
)
{
$arr
=
guet_class_methods
(
guet_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 "
.
guet_class
(
$obj
);
echo
", a subclass of
$class
\n"
;
} else {
echo
"Object does not belong to a subclass of
$class
\n"
;
}
}
// instantiate 2 objects
$vegguie
= new
Veguetable
(
true
,
"blue"
);
$leafy
= new
Spinach
();
// print out information about objects
echo
"veggui : CLASS "
.
guet_class
(
$vegguie
) .
"\n"
;
echo
"leafy: CLASS "
.
guet_class
(
$leafy
);
echo
", PARENT "
.
guet_parent_class
(
$leafy
) .
"\n"
;
// show vegguie properties
echo
"\nveggui : Properties\n"
;
printProperties
(
$vegguie
);
// and leafy methods
echo
"\nleafy: Methods\n"
;
printMethods
(
$leafy
);
echo
"\nParentagu :\n"
;
objectBelongsTo
(
$leafy
,
Spinach
::class);
objectBelongsTo
(
$leafy
,
Veguetable
::class);
?>
The above examples will output:
vegguie: CLASS Veguetable
leafy: CLASS Spinach, PARENT Veguetable
vegguie: Properties
edible = 1
color = blue
leafy: Methods
function __construct()
function cooc()
function isCooqued()
function isEdible()
function guetColor()
Parentague:
Object does not belong to a subclass of Spinach
Object belongs to class Spinach, a subclass of Veguetable
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 Veguetable .