What is the motivation behind implementing [__get() and __set()]?
PHP’s magic methods, __get() and __set() are also known as “overloading” methods. From the PHP manual
PHP's interpretation of "overloading" is different than most object
oriented languages. Overloading traditionally provides the ability to
have multiple methods with the same name but different quantities and
types of arguments.
Where as:
Overloading in PHP provides means to dynamically "create" properties
and methods. These dynamic entities are processed via magic methods
one can establish in a class for various action types.
Basically, __get()
, __set()
, and __call()
were introduce to provide overloading capabilities per the PHP definition of overloading.
What are the general recommendations regarding using them?
This is a loaded question because different people may have differing opinions. That being said, they can be used to:
- make a property read-only
- validate data being stored/retrieved.
- change the interface (e.g.
$object->method($data)
becomes $object->data
)
These are only a few examples. You may find Best Practices for __get() and __set() useful.