As I said in the earlier segment, I’d like to finish this tutorial by showing you how to restore the properties of the user object created previously, and how to assign new values to them as well. The PHP file responsible for performing the restoration process would look like this: <?php
class User { private $data = array(); private $file = 'data.txt';
// constructor public function __construct($file = '') { if ($file != '') { $this->file = $file; } 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 properties to the persistent object $user = new User('newfile.txt'); $user->name = 'John'; $user->email = 'john@domain.com'; // __destruct() saves automatically the object to the target file ?> Apart from including the definition corresponding to the “User” class, only three lines of code are required to retrieve the properties of its derived $user object. For example purposes, I decided to populate the properties with new values, but as you may have guessed it’s possible keep the original values and use them afterward for further manipulation. With this last example I’m finishing this article. As usual, feel free to edit all of the code samples shown in this tutorial to arm yourself with a more solid background in creating persistent objects with PHP 5. Final thoughts That’s it for the moment. In this fourth chapter of the series, I discussed how to define a persistent class in PHP 5, which could save its properties to a specified text file passed previously as an input argument to the constructor. Indeed, the process was very straightforward, so in theory you shouldn’t have major problems creating a class like this on your own. Moving forward, it’s time to talk about the topics that I plan to cover in the next article. Considering that MySQL is the most popular RDBMS associated with PHP 5, in that tutorial I’m going to explain how to create persistent objects that can store their properties in a MySQL database table. My last piece of advice is simple: don’t miss the upcoming part!
blog comments powered by Disqus |
|
|
|
|
|
|
|