Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does __get() and __set() mean leaky encapsulation?

Tags:

oop

php

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.

like image 366
Pitchinnate Avatar asked Jan 27 '26 07:01

Pitchinnate


1 Answers

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).

like image 133
Shoe Avatar answered Jan 29 '26 22:01

Shoe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!