As I see it, there are three approaches to accessing object properties in PHP:
1. Magic Methods
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;
}
}
2. Naive Getters and Setters
public function setName($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
3. Directly
// Set name
$dog->name = "rover";
// Get name
$name = $dog->name;
My question is when should these approaches be used/avoided? (ie. What are the pros and cons of each?).
Purely in terms of speed, I've done some profiling and there's large performance differences between the three. On my machine, a million accesses took on average:
Magic Methods Speed
0.58 seconds
Naive Getters and Setters Speed
0.13 seconds
Direct Access Speed
0.05 seconds
Link: Complete results
That would seem to indicate the Magic Methods should be avoided unless necessary, and the same for naive getters and setters, but (of course) that's it's only a fraction of a second per million accesses on my machine, and "premature optimization is the root of all evil", as the saying goes.
So maybe speed shouldn't be the defining factor.
Obviously you may wish to do validation on the properties, so I can see how naive getters and setters would be useful with that, too.
So when should each of these approaches be used? What situations are they best suited to?
I realise this may be closed for being primarily opinion based, but I'm taking a chance that some good answers, with logic and data to back them up, might be generated :) Let's see!