In OO programming would it be looked down upon to use the magic methods __get() and __set(), do these cause encapsulation to leak out of a class? For example:
class User {
private $username;
private $password;
public function __set($name,$value) {
$this->$name = $value;
}
public function __get($name) {
return $this->$name;
}
}
This effectively makes private/protected variables public.
Your code:
class User {
private $username;
private $password;
public function __set($name,$value) {
$this->$name = $value;
}
public function __get($name) {
return $this->$name;
}
}
is totally unnecessary in this case.
Encapsulation does not mean "a bunch of getters and setters". You can just refactor it to:
class User {
public $username;
public $password;
}
and as far as encapsulation is concerned, they are equivalent.
In general __get and __set have some uses, but if you can do without, you should (especially considering that they are "considerably slower" than normal method definitions).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With