HomePHP The Isset and Unset Magic Functions in PHP 5
The Isset and Unset Magic Functions in PHP 5
Welcome to the second part of a seven-part series on the magic functions in PHP 5. In the previous article, we looked at property overloading with the get and set functions. In this one, we'll take a look at the same task using the isset and unset magic functions.
As you may have heard, PHP 5 comes packaged with a set of unimplemented functions that are popularly known as “magic functions” or “magic methods.” These are called internally by the PHP engine when performing a number of tasks, such as including classes that haven’t been found at runtime, when attempting to assign values to undeclared properties of a class, or when a script tries to call a non-existent method, only to cite a few examples.
Also, magic functions will be invoked transparently by the PHP parser when serializing and unserializing objects, as well as when creating and destroying instances of a class. This allows us to execute additional processes and trigger predefined actions behind scenes in an easy way.
Obviously, giving a concrete implementation to this arsenal of functions permits us to do to all sorts of clever things with a minimal amount of code. Please remember that this may eventually be detrimental to the readability and maintenance of an application.
Despite these issues, there are times when the implementation of particular magic functions, like “__set()” and “__get()” for instance, comes in handy for easily overloading properties of a class. And now that I've brought the subject to the table, in the first chapter of this series, I used a variety of code samples to demonstrate how to overload properties of a sample class called “User” by using the complementary “__set()” and “__get()” magic functions.
Those examples showed how to dynamically create undeclared properties of the aforementioned class; they also demonstrated how to retrieve their values, either for display purposes or for further processing.
However, overloading properties is only one of the many useful things that can be accomplished with magic functions. It’s also possible to perform additional tasks when working with the “isset()” and “unset()” PHP functions, but in this case by using another set of complementary functions, called “__isset()" and “__unset()” respectively.
So, in the next few lines I’m going to delve more deeply into the advantages of using property overloading, and then take a close look at the team composed of the “__isset() “ and “__unset()” magic functions, so you can quick grasp how to use them in concrete situations.
Now, let’s get rid of the rather boring theory and continue discovering the real power behind working with magic functions in PHP 5. Let’s go!