Showing All Declared Classes

Today on the PHP-general mailing list, a question was asked regarding the usage of a new class in PHP5 beta 4. Being the ignorant programmer that I am, I responded asking where this person saw the class in question. I thought it was perhaps a PEAR package (since it wasn’t in the PHP manual) and that the person was merely a newbie asking a dumb question. (You know the old adage that there are no stupid questions; well, I disagree when the PHP manual has been completely overlooked in favor of just asking blankly on the mailing list.)

Boy, was I wrong. I ended up being the stupid person, and I learned a new and interesting trick.

It seems that I’m going to have to sit down and read the PHP manual through in full. It’s chock-full of interesting functions that I know nothing about but that are extremely useful. In fact, I learn something new everyday. Today was one such day.

I learned about the existence of the get_declared_classes() function. This function exposes all the classes that that are currently defined; it returns an array with their names. Using this array, you can expose the methods of each class. If your application/script has no user-defined classes, you’ll get a good look at all the intrinsic classes of your PHP installation.

The following function uses get_declared_classes() in conjunction with get_class_methods() to write out all defined classes and their methods:

<?php
function show_all_declared_classes()
{
$classes = get_declared_classes();
foreach($classes as $class)
{
echo $class . "\n\n";
$methods = get_class_methods($class);
foreach($methods as $method)
{
echo "\t" . $method . "\n";
}
echo "\n\n";
}
}
?>

Just call it with show_all_declared_classes() and voila! You’ll see a list of all defined classes and their methods. The person on PHP-general was using a similar function to list all the defined classes in PHP5 beta 4, and the question was related to a class seen in the print out.