Possible Duplicate:
Are Magic Methods Best practice in PHP?
These are simple examples, but imagine you have more properties than two in your class.
What would be best practice?
a) Using __get and __set
class MyClass {
private $firstField;
private $secondField;
public function __get($property) {
if (property_exists($this, $property)) {
return $this->$property;
}
}
public function __set($property, $value) {
if (property_exists($this, $property)) {
$this->$property = $value;
}
}
}
$myClass = new MyClass();
$myClass->firstField = "This is a foo line";
$myClass->secondField = "This is a bar line";
echo $myClass->firstField;
echo $myClass->secondField;
/* Output:
This is a foo line
This is a bar line
*/
b) Using traditional setters and getters
class MyClass {
private $firstField;
private $secondField;
public function getFirstField() {
return $this->firstField;
}
public function setFirstField($firstField) {
$this->firstField = $firstField;
}
public function getSecondField() {
return $this->secondField;
}
public function setSecondField($secondField) {
$this->secondField = $secondField;
}
}
$myClass = new MyClass();
$myClass->setFirstField("This is a foo line");
$myClass->setSecondField("This is a bar line");
echo $myClass->getFirstField();
echo $myClass->getSecondField();
/* Output:
This is a foo line
This is a bar line
*/
In this article: http://blog.webspecies.co.uk/2011-05-23/the-new-era-of-php-frameworks.html
The author claims that using magic methods is not a good idea:
First of all, back then it was very popular to use PHP’s magic functions (__get, __call etc.). There is nothing wrong with them from a first look, but they are actually really dangerous. They make APIs unclear, auto-completion impossible and most importantly they are slow. The use case for them was to hack PHP to do things which it didn’t want to. And it worked. But made bad things happen.
But I would like to hear more opinions about this.
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 :
@property
phpdoc annotation but that requires to maintain them: quite a pain)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.