As I said in the previous section, it’d be desirable to extend the functionality of the example “User” class by making it able to save its properties to a different text file. This can be achieved in several ways, but in this case I’m simply going to redefine the class’s constructor, as shown below: 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); } } As you can see above, now the constructor of the “User” class has been slightly modified to accept as an incoming argument the name of the file that will be used to store the corresponding properties. This subtle change definitely permits much more more flexibility when creating a persistent object. To understand this concept more clearly, I suggest that you look at the following code sample. It will first spawn a new user object, and then assign some basic properties dynamically; finally, it will save those properties to a different text file, this time called “newfile.txt.” Here’s the example: // example on creating a persistent object $user = new User('newfile.txt'); $user->name = 'Alejandro'; $user->email = 'alejandro@mydomain.com'; // __destruct() saves automatically the object to the target file Undeniably, the previous code fragment is very easy to follow, so I won’t bore you by explaining once again how it works. It's valid to note here, though, how a small change introduced into the originating class of this persistent object can have a considerable impact on its functionality. Pretty good, right? At this point, naturally the properties of the previous user object have been neatly saved to the target “newfile.txt” file, but this is only the half of the story. It's necessary to show how those properties can be retrieved in a different file, thus proving that they’re capable of persisting across different HTTP requests. With that goal in mind, in the last section of this tutorial I’m going to code another short script, which will illustrate the full details of this retrieval process. Now, click on the link that appears below and read the final segment. We’re almost finished!
blog comments powered by Disqus |
|
|
|
|
|
|
|