Hacking with PHP has been updated for PHP 7 - click here! >>

Helpful utility functions

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:

    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.


If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: Interfaces >>

Previous chapter: Static data

Jump to:


Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.