OOP in PHP (part II)
Time to discover the hidden powers of the object oriented programming in PHP. Today I’ll describe the usage of serialisation, the secrets of overloading and - probably the most useful thing today - design patterns.
Serialisation
As you remember from the first part of the article, objects are completely different type of variables. You could easily write a string, number or even an array to a file… but what about objects? You can’t just write an object to a file, as PHP will try to convert it to a string, which is technically impossible, and will result in throwing an error. Yeah, I guess you can already suppose that there’s a solution.
Actually, all you have to do to serialise an object (i.e. make it writable to a file) is use one function: serialize(). As you can guess, using unserialize() function will allow you to have your object back once it has been saved to a file. Remember to define the object’s class before unserialising it, otherwise it will become useless.
Methods __sleep() and __wakeup() make serialisation in PHP5 even easier. They are called, respectively, before an object is serialised or unserialised. They are very useful e.g. for closing and reopening database connections, or saving additional information about the serialisation process. Remember that the __sleep() magic function has to return an array of all members that should be serialised.
class AutoStalker {
private $filename, $file;
public function __construct($filename) {
$this->filename = $filename;
$this->open();
}
public function prepare_for_stalking() {
$this->file = fopen($this->filename, 'a');
}
public function stalk($text) {
fwrite($this->file, $text."\n");
}
public function see_whos_been_stalked() {
return file_get_contents($this->filename);
}
public function __wakeup() {
$this->prepare_for_stalking();
}
public function __sleep() {
fclose($this->file);
return array('filename');
}
}
In the example above, I only serialise the file’s name, because we don’t need any additional information to open that file in the future.
Now, let’s see something more useful; how about using some PHP cookies?
