Although PHP was originally conceived as a procedural language, object-oriented features have been incorporated into every major release going all the way back to version 3. Offering a compliment of features such as
interfaces,
namespaces, and
inheritance, developers hailing from other object-oriented languages such as Java and C++ can quickly adapt to PHP with little trouble.
Indeed, object-oriented programming (OOP) has become so pervasive within the PHP community that many choose to employ the approach at every opportunity. One great way to incorporate more OOP into your applications is through the
Standard PHP Library (SPL), a powerful yet largely unknown extension made part of the official PHP language with the PHP 5.0 release. The SPL provides a series of classes which extend the PHP language in numerous ways, offering object-oriented
advanced data structures,
iterators, and
file handlers, among other features.
In this tutorial I'll introduce you to several of my favorite SPL iterators, providing you with the basis from which you can continue your own exploration. Following several examples, I'll conclude with a brief introduction to other key SPL features.
The SPL provides over 20 classes useful for iterating over and manipulating different types of data, including arrays, directories, files, and XML. For instance the
ArrayIterator class is useful for interacting with arrays. Consider for instance the following array:
$platforms = array('Nintendo DS', 'PlayStation 2', 'PlayStation 3');
// Load the array into an array object
$platformArray = new ArrayObject($platforms);
// Append a new platform to the end of the array
$platformArray->append('Xbox 360');
// Determine the array size
printf("Tracking %d platforms:
", $platformArray->count());
// Iterate over the array, outputting each array element
for($i = $platformArray->getIterator(); $i->valid(); $i->next())
{
printf("%s
", $i->current());
}
Several recent projects have involved interaction with the server's file system, including using PHP to learn more about how many images reside in a specific directory. You can use the SPL's
DirectoryIterator class to easily navigate a directory, to learn more about the files, file permissions, and file owners, among other things. Consider a directory named
images, which contains the following five images:
house.png,
icon.gif,
logo.jpg,
truck.png and
vacation.png. The following snippet can be used to parse this directory in order to determine how many different file types exist:
Executing this snippet produces the following results (formatted for readability):