Best practice: PHP Magic Methods __set and __get
You only need to use magic if the object is indeed "magical". If you have a classic object with fixed properties then use setters and getters, they work fine.
If your object have dynamic properties for example it is part of a database abstraction layer, and its parameters are set at runtime then you indeed need the magic methods for convenience.
I have been exactly in your case in the past. And I went for magic methods.
This was a mistake, the last part of your question says it all :
- this is slower (than getters/setters)
- there is no auto-completion (and this is a major problem actually), and type management by the IDE for refactoring and code-browsing (under Zend Studio/PhpStorm this can be handled with the
@property
phpdoc annotation but that requires to maintain them: quite a pain) - the documentation (phpdoc) doesn't match how your code is supposed to be used, and looking at your class doesn't bring much answers as well. This is confusing.
- added after edit: having getters for properties is more consistent with "real" methods where
getXXX()
is not only returning a private property but doing real logic. You have the same naming. For example you have$user->getName()
(returns private property) and$user->getToken($key)
(computed). The day your getter gets more than a getter and needs to do some logic, everything is still consistent.
Finally, and this is the biggest problem IMO : this is magic. And magic is very very bad, because you have to know how the magic works to use it properly. That's a problem I've met in a team: everybody has to understand the magic, not just you.
Getters and setters are a pain to write (I hate them) but they are worth it.