Search code examples
phpoopencapsulationaccessor

Why make class variables private?


Completely new to OOP programming, so sorry if the answer is obvious. I've seen many YouTube tutorials where the code is as following:

class myClass{
    private $myVar;

    function getVar(){
        return $this->myVar;
    }
}

myObject = new myClass();
print myObject->getVar();

but why is it preferable to make the variable private and then access it through a function, rather than just using myObject->myVar?


Solution

  • A few benefits of private variables:

    1. Nobody can change it from the outside without your permission. If this variable is important for internal state, having somebody externally access it can be disastrous when you need to use it next (because of a different method call on your class). This is a big deal.
    2. If somebody calls "get" on it, you can intercept it and create side effects if needed (for accounting reasons for example; note that "magic" behind the scenes is generally not a good idea from just a pure accessor).
    3. The value returned from a "get" may not be a real concrete value, but the result of a calculation. You expose it via the method, but it doesn't really need to be cached internally.

    You may also see here.

    Was this helpful?