PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1
CHAPTER 5 ■ OBJECT TOOLS

Again, I make some assumptions about the location of class files and directories and their
relationship to either namespaces or PEAR-style classnames. You might be concerned about the various
ways in which we can call a class in a namespace, given the flexibility of importing and aliasing. After all,
I could use an alias to call business\ShopProduct anything I want. Percy, for example. The good news is
that the value that is passed to autoload is always normalized to a fully qualified name, without a
leading backslash.
Depending on the organization of your classes and files, the
autoload() function can be a useful
way of managing your library inclusions.


■Note .__autoload is a powerful tool, but it does have some limitations. In particular, you can only define it


once in a process. If you need to change your autoload function dynamically you should look at the


spl_autoload_register function (http://www.php.net/spl_autoload_register), which supports that


functionality.


The Class and Object Functions


PHP provides a powerful set of functions for testing classes and objects. Why is this useful? After all, you
probably wrote most of the classes you are using in your script.
In fact, you don’t always know at runtime about the classes that you are using. You may have
designed a system to work transparently with third-party bolt-on classes, for example. In this case, you
will typically instantiate an object given only a class name. PHP allows you to use strings to refer to
classes dynamically like this:


// Task.php


namespace tasks;


class Task {
function doSpeak() {
print "hello\n";
}
}


// TaskRunner.php


$classname = "Task";


require_once( "tasks/{$classname}.php" );
$classname = "tasks\$classname";
$myObj = new $classname();
$myObj->doSpeak();


This script might acquire the string I assign to $classname from a configuration file or by comparing
a web request with the contents of a directory. You can then use the string to load a class file and
instantiate an object. Notice that I’ve constructed a namespace qualification in this fragment.

Free download pdf