PHP Property Accessors
From Wikipedia, "...a property is a special sort of class member, intermediate between a field (or data member) and a method."
PHP doesn't have clean property accessors like Ruby or Python. As you'll see, it is verbose. We'll also view Ruby and Python implementations. For all examples, our property accessor is calculating a value from two public instance variables or members.
Ruby's access method:
Python's built-in function property:
In PHP, when we calculate a properties value, we have to explicitly call the method. It would be nice for the object's properties to all have the same API.
We can have the same API by implementing property overloading with the magic method __get.
For this simple example, the use of __get is overkill. However, this methodology is really useful with larger classes that have many public members and require multiple calculated properties. Once the larger class is instantiated, the API is consistent. You don't need to reference the class to ask, "is this property a method or a member?"
Notes
- Code tested in Ruby 1.9, Python 2.5 and PHP 5.2.