In the previous segment, the properties assigned to an object derived from the sample “User” class were saved to a text file. Having discussed the underlying logic of this process, the only thing that remains undone is showing how those properties can be easily retrieve by a different PHP file. Taking into account this requirement, below I defined such a file. It performs the retrieval process and assigns new values to the respective properties before storing them again in the target file. Here’s how this file looks: <?php
class User { private $data = array(); private $file = 'data.txt';
// constructor public function __construct() { list($this->data['name'], $this->data['email']) = explode('|', file_get_contents($this->file)); }
// set undeclared property public function __set($property, $value) { if ($property !== 'name' and $property !== 'email') { return; } $this->data[$property] = $value; }
// get undeclared property public function __get($property) { if (isset($this->data[$property]) === TRUE) { return $this->data[$property]; } }
// save object to session variable public function __destruct() { file_put_contents($this->file, $this->name . '|' . $this->email); } }
// assign new values to properties of the persistent object $user = new User(); $user->name = 'Susan'; $user->email = 'susan@domain.com'; // __destruct() saves automatically the object to the target file
?> Hopefully, if all has gone well, after running the previous file, the name and email of my friend Susan have been saved to the “data.txt” file. thus preserving these properties for further handling. This example proves how simple it is to create objects that are capable of saving their properties to a predefined text file. Of course, it’s valid to point out that in this case only the object’s properties are stored, so if an application also needs to preserve the methods, then an approach that uses serialization/unserialization would probably be the best option to pick up. Finally, feel free to introduce your own enhancements to the example class shown before, so you can sharpen your existing skills in building persistent objects in PHP 5. Final thoughts In this third part of the series, you learned how to build a basic PHP 5 class that could store instances of itself to a predefined text file, thus exploring yet another approach to creating persistent objects in a straightforward fashion. In the upcoming tutorial, I’m going to enhance the existing functionality of this sample class by providing it with the capacity for using different text files as its default storage mechanism. Here’s my final piece of advice: don’t miss the next part!
blog comments powered by Disqus |
|
|
|
|
|
|
|