Before I start explaining how to use the “__isset()” and “__unset()” magic functions, it would be helpful to reintroduce the example developed in the preceding tutorial. It demonstrated how to use the “__set()” and “__get()” methods for overloading a basic user-related class. Having said that, here’s the complete source code corresponding to that sample class: 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; } } } I’m not going to explain again how the above “User” class does its business, since this was already covered in depth in the previous tutorial. Instead, I’m going create a short script that shows how to dynamically add some properties to the class in question, and to retrieve their respective values. So, basically the script that performs all of these interesting tasks looks like this: // example of usage of 'User' class with property overloading $user = new User(); $user->fname = 'Alejandro'; $user->lname = 'Gervasio'; $user->email = 'alejandro@mydomain.com'; $user->address = 'My address 1234';
// display user data echo 'First Name: ' . $user->fname . ' Last Name: ' . $user->lname . ' Email: ' . $user->email . ' Address: ' . $user->address; /* displays the following First Name: Alejandro Last Name: Gervasio Email: alejandro@mydomain.com Address: My address 1234 */ There you have it. By giving a concrete implementation to the “__set()” and “__get()” functions, it is possible to add new properties to the “User” class without having to declare them explicitly. Of course, in doing so the whole source code of the class might become less readable. Unfortunately, that’s the price that must be to paid when it comes to overloading class properties. So far, so good. At this stage you've hopefully become familiar with using the handy “__set()” and “__get()” magic functions. Given the inherent flexibility these function provide, it’s also feasible to modify their implementation and give them the capacity to determine which properties of a class to create and which to avoid creating, by means of a simple control mechanism. Assuming that you’re interested in learning how to build this checking mechanism, in the section to come I’m going to change the definition of the previous “User” class so it can restrict the creation of undeclared properties according to a predefined schema. To see how this will be accomplished, click on the link below and keep reading.
blog comments powered by Disqus |
|
|
|
|
|
|
|