PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1

CHAPTER 5 ■ OBJECT TOOLS


Typically, you would do something like this when you want your system to be able to run user-
created plug-ins. Before you do anything as risky as that in a real project, you would have to check that
the class exists, that it has the methods you are expecting, and so on.
Some class functions have been superseded by the more powerful Reflection API, which I will
examine later in the chapter. Their simplicity and ease of use make them a first port of call in some
instances, however.


Looking for Classes


The class_exists() function accepts a string representing the class to check for and returns a Boolean
true value if the class exists and false otherwise.
Using this function, I can make the previous fragment a little safer.


// TaskRunner.php
$classname = "Task";


$path = "tasks/{$classname}.php";
if (! file_exists( $path ) ) {
throw new Exception( "No such file as {$path}" );
}


require_once( $path );
$qclassname = "tasks\$classname";
if (! class_exists( $qclassname ) ) {
throw new Exception( "No such class as $qclassname" );
}


$myObj = new $qclassname();
$myObj->doSpeak();


Of course, you can’t be sure that the class in question does not require constructor arguments. For
that level of safety, you would have to turn to the Reflection API, covered later in the chapter.
Nevertheless, class_exists() does allow you to check that the class exists before you work with it.


■Note Remember, you should always be wary of any data provided by outside sources. Test it and treat it before


using it in any way. In the case of a file path, you should escape or remove dots and directory separators to


prevent an unscrupulous user from changing directories and including unexpected files.


You can also get an array of all classes defined in your script process using the
get_declared_classes() function.


print_r( get_declared_classes() );


This will list user-defined and built-in classes. Remember that it only returns the classes declared at
the time of the function call. You may run require() or require_once() later on and thereby add to the
number of classes in your script.

Free download pdf