In the previous segment, you learned how to give a concrete implementation to the "__set()" and "__get()" magic functions within a simple class to assign to it undeclared properties at run time. You also learned how to fetch values in a straightforward manner.
Now, it's time to demonstrate how to take advantage of these functions by means of a concrete example. Below I wrote a short script, which shows how to dynamically assign four properties to the "User" class that naturally have no explicit declaration.
Here's how this script looks:
// example of usage of 'User' class with property overloading
$user = new User();
$user->fname = 'Alejandro';
$user->lname = 'Gervasio';
$user->email = 'email@example.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: firstname.lastname@example.org Address: My address 1234
Regardless of the simplicity of the above example, it demonstrates how useful the "__set()" and "__get()" magic functions can be when it comes to overloading properties of a class.
As you may have noticed, on one hand the script creates four new properties for the class and assigns to them some trivial values, while on the other hand those values are retrieved "behind the scenes" via the pertinent "__get()" method. Simple to code, even when it's not so simple to read, right?
The previous phrase is an adequate epilogue for this first installment of the series. As I explained before, the implementation of the "__set()" and "__get()" magic functions is a powerful approach that must be used very carefully.
Undeniably, it's possible to perform all sorts of clever tasks via these functions, but this versatility comes at a cost. In general, it may be harder to read and understand how a class is handling its properties. Anyway, PHP 5 gives you the chance to use property overloading in an easy way, so go ahead and give it a try!
That's all for the moment. In this introductory part of the series, I explained how to implement and use the "__set()" and "__get()" magic functions included with PHP 5, which allow you to overload the properties of a class very easily.
It's not new to say that property overloading is a powerful approach that can be used to perform all sorts of clever tasks, but as I explained, it must be used carefully, and certainly not abused.
In the next part of the series I'm going to explain how to use the "__isset()" and "__unset()" magic functions, so don't miss the upcoming tutorial!
blog comments powered by Disqus