Getter and Setter?
You can use php magic methods __get
and __set
.
<?php
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;
}
return $this;
}
}
?>
Why use getters and setters?
- Scalability: It's easier refactor a getter than search all the var assignments in a project code.
- Debugging: You can put breakpoints at setters and getters.
- Cleaner: Magic functions are not good solution for writting less, your IDE will not suggest the code. Better use templates for fast-writting getters.
Google already published a guide on optimization of PHP and the conclusion was:
No getter and setter Optimizing PHP
And no, you must not use magic methods. For PHP, Magic Method are evil. Why?
- They are hard to debug.
- There is a negative performance impact.
- They require writing more code.
PHP is not Java, C++, or C#. PHP is different and plays with different roles.