In order to illustrate how lazy loading can also be used successfully with the properties of a class, I'm going to redefine the previous "User" class so it can create properties dynamically. Having explained this, take a look at the brand new definition of "User," which now is as follows: class User { private $data = array();
// constructor (not implemented) public function __construct(){}
// implement '__set()' magic method public function __set($name, $value) { if (!isset($this->data[$name])) { $this->data[$name] = $value; } }
// implement '__get()' magic method public function __get($name) { if (isset($this->data[$name])) { return $this->data[$name]; } }
// implement '__toString()' magic method public function __toString() { $str = ''; foreach ($this->data as $property => $value) { $str .= 'Property: ' . $property . ' Value: ' . $value . '<br />'; } return $str; } } For obvious reasons, building a class that's only comprised of a few magic PHP 5 methods isn't a good thing at all, but given that I plan to use it for demonstrative purposes I recommend that you study its signature closely to grasp its underlying logic. As shown above, apart from implementing the already familiar "__toString()" method, the class does the same thing with the complementary "__set()" and "__get()" tandem, which permits it to dynamically create and retrieve undeclared properties, a process commonly known in PHP 5 as property overloading. It's quite possible that at this moment you're wondering what the point is in implementing the "__set()" and "__get()" magic methods. Considering that they can be used for creating and fetching properties on request, then it'd be correct to say that those properties could be brought to life in a true "lazy" way. That's a quite interesting concept, isn't it? Of course, in most cases using property overloading can make the code of classes difficult to read and harder to follow. However, in this particular example this approach comes in handy for demonstrating how easy it is to use lazy loading when creating the properties of a basic class. But if you're like me, you'll want to see an example that shows how to work with the modified version of the previous "User" class. Therefore, in the course of the section to come I'm going to build a simple script that will lazily assign properties to that class. To see how this script will be developed, go ahead and read the following segment. It's only one click away.
blog comments powered by Disqus |
|
|
|
|
|
|
|