Page 195 - Open Soource Technologies 304.indd
P. 195
Unit 8: Objects
8.6.2. Examining an Object Notes
To get the class to which an object belongs, first make sure it is an object using the is_object( )
function, then get the class with the get_class( )function:
$yes_no = is_object(var); $classname = get_class(object);
Before calling a method on an object, you can ensure that it exists using the method_exists( )
function:
$yes_no = method_exists(object, method);
Calling an undefined method triggers a runtime exception.
Just as get_class_vars( ) returns an array of properties for a class, get_object_vars( ) returns an
array of properties set in an object:
$array = get_object_vars(object);
And just as get_class_vars( ) returns only those properties with default values, get_object_vars
( ) returns only those properties that are set:
class Person { var $name; var $age; } $fred = new Person; $fred->name = ‘Fred’; $props =
get_object_vars($fred); // $props is array(‘name’ => ‘Fred’);
The get_parent_class( ) function actually accepts either an object or a class name. It returns the
name of the parent class, or FALSE if there is no parent class:
class A {} class B extends A {} $obj = new B; echo get_parent_class($obj); // prints A echo
get_parent_class(B); // prints A
8.6.3 Sample Introspection Program
Example shows a collection of functions that display a reference page of information about an
object’s properties, methods, and inheritance tree.
Object introspection functions.
// return an array of callable methods (include inherited methods) function get_methods($object)
{
$methods = get_class_methods(get_class($object));
if(get_parent_class($object))
{
$parent_methods = get_class_methods(get_parent_class($object));
$methods = array_diff($methods, $parent_methods);
}
return $methods;
} // return an array of inherited methods function
get_inherited_methods($object)
{
$methods = get_class_methods(get_class($object));
if(get_parent_class($object))
{
LOVELY PROFESSIONAL UNIVERSITY 189