13.09.2016 Views

PHP and MySQL Web Development 4th Ed-tqw-_darksiderg

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

190 Chapter 6 Object-Oriented <strong>PHP</strong><br />

The ObjectIterator class has a set of functions as required by the Iterator interface:<br />

n<br />

n<br />

n<br />

n<br />

n<br />

n<br />

The constructor is not required but is obviously a good place to set up values for<br />

the number of items you plan to iterate over <strong>and</strong> a link to the current data item.<br />

The rewind() function should set the internal data pointer back to the beginning<br />

of the data.<br />

The valid() function should tell you whether more data still exists at the current<br />

location of the data pointer.<br />

The key() function should return the value of the data pointer.<br />

The value() function should return the value stored at the current data pointer.<br />

The next() function should move the data pointer along in the data.<br />

The reason for using an iterator class like this is that the interface to the data will not<br />

change even if the underlying implementation changes. In this example, the<br />

IteratorAggregate class is a simple array. If you decide to change it to a hash table or<br />

linked list, you could still use a st<strong>and</strong>ard Iterator to traverse it, although the Iterator<br />

code would change.<br />

Converting Your Classes to Strings<br />

If you implement a function called __toString() in your class, it will be called when<br />

you try to print the class, as in this example:<br />

$p = new Printable;<br />

echo $p;<br />

Whatever the __toString() function returns will be printed by echo.You might, for<br />

instance, implement it as follows:<br />

class Printable<br />

{<br />

public $testone;<br />

public $testtwo;<br />

public function __toString()<br />

{<br />

return(var_export($this, TRUE));<br />

}<br />

}<br />

(The var_export() function prints out all the attribute values in the class.)<br />

Using the Reflection API<br />

<strong>PHP</strong>’s object-oriented features also include the reflection API. Reflection is the ability to<br />

interrogate existing classes <strong>and</strong> objects to find out about their structure <strong>and</strong> contents.<br />

This capability can be useful when you are interfacing to unknown or undocumented<br />

classes, such as when interfacing with encoded <strong>PHP</strong> scripts.<br />

The API is extremely complex, but we will look at a simple example to give you<br />

some idea of what it can be used for. Consider the Page class defined in this chapter, for

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!