In the previous segment, I created a basic "User" class, whose API allowed us to easily assign and retrieve the values of its declared properties. However, as I expressed earlier, it's possible to shorten its definition and make it more "dynamic" simply by concretely implementing the "__set()" and "__get()" methods. To demonstrate this concept a bit more, I'm going to redefine this sample class to allow us not only to create new class properties at run time, but retrieve their respective values with extreme ease. Now that you know what I'm going to do in the next few lines, please examine the modified version of the "User" class. It now looks like this: class User { // constructor (not implemented) public function _construct(){}
// set undeclared property function __set($property, $value) { $this->$property = $value; }
// get defined property function __get($property) { if (isset($this->$property)) { return $this->$property; } } } Now, suddenly things are much more interesting than in the example shown in the previous section. As you can see above, the "User" class is only comprised of two methods -- the corresponding "__set()" and "__get()" functions. And in this specific situation, they have been given a concrete implementation. In the first case, the "__set()" function will create an undeclared property and assign a value to it, while in the last case, its counterpart "__get()" will retrieve this value if the property has been previously set. The implementation of these two methods permits us to overload properties in a truly simple way. It also makes the class's source code much shorter and more compact. But, as with everything in life, this process has some disadvantages that must be taken into account. First, and most importantly, the lack of an explicit declaration for each property of the class makes the code harder to read and follow. Second, it's practically impossible for an IDE to keep track of those properties for either commenting or documenting them. Logically, this is something that must be evaluated consciously when overloading the properties of a class. Its implementation depends strongly on the context where it will be used. Now, returning to the previous example class, given that it's already been modified, it's time to give it a try, right? So, with that idea in mind, in the next section I'm going to create an example that will show how to assign undeclared properties to it, and how to retrieve their values. Don't waste more time; read the following segment. It's only one click away
blog comments powered by Disqus |
|
|
|
|
|
|
|