Hudzilla.org - the homepage of Paul Hudson
Contents > Objects Wish List | Report Bug | About Me ]

6.16     Helpful utility functions: class_exists(), get_class(), and get_declared_classes()

This is NOT the latest copy of this book; click here for the latest version.

bool class_exists ( string class_name)

bool get_class ( object object)

array get_declared_classes ( void )

There are three particular OOP-related functions that will make your life easier, and these are class_exists(), get_class(), and get_declared_classes(). In order, class_exists() returns true if the specified class has been declared, get_class() returns the class name of the object you pass to it, and get_declared_classes() returns an array of all classes that you can currently create an object of.

Here are some examples:

<?php
    
if ($foo == $bar) {
        
$sam = new employee;
    } else {
        
$sam = new dog;
    }

    print
"Sam is a " . get_class($sam) . "\n";
    print
"Class animal exists: " . class_exists("animal") . "\n\n\n\n";
    print
"All declared classes are: " . get_declared_classes() . "\n";
?>

As you can see, the most common use for get_class() is when one object can be of several possible types, as in the code above. C++ users will be familiar with the concept of Runtime Type Information (RTTI), and this is pretty much the same thing.





<< 6.15 Static data   6.17 Interfaces: get_declared_interfaces() >>
Table of Contents
Want to see this stuff in print? PHP in a Nutshell takes the core topics covered here, adds in thousands of edits from the editorial team and myself, and combines them to make an unbeatable reference for PHP programmers at all levels.



My latest book has hundreds more tips on how to use PHP, Apache, and MySQL, plus Perl, Python, shell scripts, performance tuning, and more!



Top-right shadow
 
Bottom-left shadow Bottom shadow

Comments from other readers
A PHP User - 06 Sep 2008

*bool get_class ( object object)
string get_class ( object object )

Guna - 06 Sep 2008

try this

var_dump(get_declared_classes());

A PHP Newbie - 06 Sep 2008

print "All declared classes are: " . get_declared_classes() . "\n";

doesn't seem to works - it prints:

All declared classes are: Array

And when you print_r this array you don't get the class names !



Add comment
Please note that by posting a comment here you are committing it to the public domain. This is important so that others can make use of your code themselves, and also so that I can incorporate helpful notes directly into the main text. Comments are limited to 2000 characters in length.

If you are reporting an error in the content, please tell me directly.

Your name/email address:
Your comment:
 
Now, in order to verify that you're a real person, please answer this simple question: what is seven plus two?
The answer is:
(please write in
numbers, eg 19)


Top-right shadow
 
Bottom-left shadow Bottom shadow