phpoopgetter-settermagic-methodsmember-access

What's the sense of the __get() & __set() methods


Today I read a Tutorial about MVC, the guy was using magic-methods (__get & __set()) to access a private member value. (LINK) First I was confused what __get and __set do, but after reading trought the Internet I finally found out, that this methods are called if the member is not accessable from the outside. So far...

But it doesn't make sense to have code like this:

class Foo {
    private $bar;

    public __set($value) {
        $this->bar = $value;
    }

    public __get() {
        return $this->bar;
    }
}

I can use normal getter and setter I guess - Its IMO a way easier to understand:

class Foo {
    private $bar;

    public setBar($value) {
        $this->bar = $value;
    }

    public getBar() {
        return $this->bar;
    }
}

If you want access the member outside with __get & __set you can also make the member public - So I don't get whats the sence of it. Can you told me (maybe with an example) whats the sense of these 2 methods?


Solution

  • You develop your program , and you consider that you do not have to control access to your attributes. You therefore put the public instead of private . But during maintenance , you realize that you need to change your class to impose a constraint such that it is forbidden to 0 to an attribute. To make this change , you need to add a setter , and spend your attribute in private. Result: it will take you to impact this change to all of this class customers.

    If you had used setters and getteurs from the beginning , maintenance would have been much simpler.