How I used PHP's magic methods and why
When PHP5 was released there were a couple new additions, magic methods. The best way to think about a magic method is a function you didn't have to write or include that helps keep your code running smoothly.
A couple of the many magic methods
__set() and __get() were used to create some neat functionality for this site.
__set()
Normally when setting variables for use on a page you need to declare each and every one of them. When doing so this invokes the __set() magic method. What happens if you try and set a variable that you don't know the name of or if it may not always exist? To use a real example, I was setting properties in my Template class that were ever changing.
When I try and set a property that does not exist, such as $this->page_id = 6;, the Template class invokes the __set($index, $value) method which results in $this->vars[page_id] = 6 being set.
__get()
The converse of the __set() method is __get(), which is invoked when you try and retrieve a variable or property that is either not set or not accessible.
Because in my above example $this->vars is private, it is inaccessible from other classes. If I wanted to change this functionality I would need to essentially change how the __get() method works, or overload it.
If I had this code in my Template class I would then be able to reference the vars property from another class. The ampersand before __get() means to use references when working with the variables. When you pass by reference it is best to forget about the value of the variable and think more about what the variable holds. Changing the value of a variable when you pass it by reference changes the value of the variable outside of the function/method as well. It is often used to 'return' multiple values without actually using the return keywords. I touched on passing by reference in a past post.
Posted: August, 31 2010
Social Media