05.05.2013 Views

Programming PHP

Programming PHP

Programming PHP

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Example 6-1. Displaying all declared classes (continued)<br />

else {<br />

foreach($methods as $method) {<br />

echo "$method( )";<br />

}<br />

}<br />

echo "$class properties:";<br />

$properties = get_class_vars($class);<br />

if(!count($properties)) {<br />

echo "None";<br />

}<br />

else {<br />

foreach(array_keys($properties) as $property) {<br />

echo "\$$property";<br />

}<br />

}<br />

echo "";<br />

}<br />

}<br />

Figure 6-1 shows the output of the display_classes( ) function.<br />

Examining an Object<br />

To get the class to which an object belongs, first make sure it is an object using the<br />

is_object( ) function, then get the class with the get_class( ) function:<br />

$yes_no = is_object(var);<br />

$classname = get_class(object);<br />

Before calling a method on an object, you can ensure that it exists using the method_<br />

exists( ) function:<br />

$yes_no = method_exists(object, method);<br />

Calling an undefined method triggers a runtime exception.<br />

Just as get_class_vars( ) returns an arrayof properties for a class, get_object_vars( )<br />

returns an array of properties set in an object:<br />

$array = get_object_vars(object);<br />

And just as get_class_vars( ) returns onlythose properties with default values, get_<br />

object_vars( ) returns only those properties that are set:<br />

class Person {<br />

var $name;<br />

var $age;<br />

}<br />

$fred = new Person;<br />

$fred->name = 'Fred';<br />

$props = get_object_vars($fred); // $props is array('name' => 'Fred');<br />

This is the Title of the Book, eMatter Edition<br />

Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.<br />

Introspection | 149

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!