It's quite possible that you haven't had the chance to read the preceding tutorial of this series, where I discussed briefly how to implement and use the "__isset()" and "__unset()" magic functions. With this in mind, I've included the example created in that article, which shows how to utilize those functions within a basic class called "User." Here's the complete source code that corresponds to the aforementioned "User" class. Have a look at it, please: class User { // constructor (not implemented) public function _construct(){}
// set undeclared property in a restrictive way public function __set($property, $value) { if (in_array($property, array('fname', 'lname', 'email')) === TRUE) { $this->$property = $value; } }
// get declared property public function __get($property) { return $this->$property; }
// implement __isset() method public function __isset($property) { echo 'Checking if property '. $property . ' has been set...'; }
// implement __unset() method public function __unset($property) { echo 'Unsetting property ' . $property; } } Now that I have listed the entire signature of the above "User" class, which shows a simple implementation of the "__isset()" and "__unset()" magic methods, please focus your attention on the following code snippet. It demonstrates how they behave when using the "isset()" and "unset()" PHP functions with an instance of the previous user-related class. Here's the corresponding code sample: $user = new User(); $user->fname = 'Alejandro'; $user->lname = 'Gervasio'; isset($user->email); /* display the following Checking if property email has been set... */
unset($user->email); /* displays the following Unsetting property email */ As you can see, using the "__isset()" and "__unset()" functions isn't too different from working with other magic methods, such as "__set()" and "__get()" that were discussed in the first tutorial. All that's required here is to give an explicit implementation to the functions and then use "isset()" and "unset()" to make the PHP engine call them automatically. It's that simple, really. Well, at this point I'm sure that you've already grasped the underlying logic of the previous example. Thus, it's time to continue exploring other PHP 5 magic functions, and that logically includes the "__call()" method mentioned in the introduction. With that idea in mind, in the following section I'm going to explain how to work with this brand new method to implement what is widely called "method overloading" in object-oriented jargon. Now, to learn more on this topic, click on the link that appears below and proceed to read the section to come. I'll be there, waiting for you.
blog comments powered by Disqus |
|
|
|
|
|
|
|