Page 193 - Open Soource Technologies 304.indd
P. 193
Unit 8: Objects
Allows for any class that extends Bar to access the print_vars() method. Since the method is Notes
abstract it is defined and does not have to be declared. The second method, some_method(),
sets up an abstract method. This method can be overridden by any child classes, however, so it
serves only to enforce the visibility (for instance, with the protected keyword any child method
of the same name must be either public or protected, but not private).
With some careful planning, a developer can utilize abstract classes and interfaces to set up
frameworks for other classes in the application. In this way the developer can expect certain
criteria to be met by various classes so that object introspection is not quite as necessary.
8.6.1 Examining Classes
To determine whether a class exists, use the class_exists( ) function, which takes in a string and
returns a Boolean value. Alternately, you can use the get_declared_classes( ) function, which
returns an array of defined classes and checks if the class name is in the returned array:
$yes_no = class_exists(classname); $classes = get_declared_classes( );
You can get the methods and properties that exist in a class (including those that are inherited
from superclasses) using the get_class_methods( ) andget_class_vars( ) functions. These functions
take a class name and return an array:
$methods = get_class_methods(classname); $properties = get_class_vars(classname);
The class name can be a bare word, a quoted string, or a variable containing the class name:
$class = ‘Person’; $methods = get_class_methods($class); $methods = get_class_methods(Person);
// same $methods = get_class_methods(‘Person’); // same
The array returned by get_class_methods( ) is a simple list of method names. The associative
array returned by get_class_vars( ) maps property names to values and also includes inherited
properties. One quirk of get_class_vars( ) is that it returns only properties that have default
values; there’s no way to discover uninitiailized properties.
Use get_parent_class( ) to find a class’s parent class:
$superclass = get_parent_class(classname);
Example lists the display_classes( ) function, which displays all currently declared classes and
the methods and properties for each.
Displaying all declared classes.
function display_classes ( )
{
$classes = get_declared_classes( );
foreach($classes as $class){
echo “Showing information about $class<br />”;
echo “$class methods:<br />”;
$methods = get_class_methods($class);
if(!count($methods)) { echo “<i>None</i><br />”;
}
else
{
LOVELY PROFESSIONAL UNIVERSITY 187