Questions
I m working on a personal project in PHP and like most classes that are built, I require getter/setter functions.
I had a thought and did some research but couldn t find an answer. Instead of defining two functions - one get and one set - why couldn t they just be handled by a single function?
function myVar ($newVar = NULL) {
if(isset($newVar)) {
$this->var = $newVar;
} else {
return $this->var;
}
}
Are there any downsides to this that I may not be seeing?
Answers
You could use __get and __set magic dust. But, there is a downside: you ll lose IDE auto completion, PHPDoc generation, inheritance. It helps not to write code, but it s not clean, you don t have public/protect/private logic. It s the same for your method.
class MyClass {
private $one;
private $two;
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;
}
}
Source
License : cc by-sa 3.0
http://stackoverflow.com/questions/29569438/php-getter-and-setter-together
Related