Why you should not access private fields, even if you can

TL;DR;
The only method accessing private (or protected) field should be it’s accessor. This accessor can has any visibility. It will save some headache for you later.

A quick example:

Assume, you’ve inherited code. Your Product model looks like this:


    private $_options

    public function getOptions()
    {
        return $this->_options;
    }

    public function getOption($code)
    {
        if (isset($this->_options[$code])) {
            return $this->_options[$code];
        }
        return null;
    }

    public function setOptions(array $options)
    {
        $this->_options = $options;
    }

As you can see – author thought that this is a good idea that you set options before you use it later in the code.

But the time came, and you have to alter that behavior. Options are needed even if they were not set before (i.e. fetched from database), so you override getOptions:

    public function getCustomOptions()
    {
        if(null == $this->_customOptions) {
            $options = $this->fairlyComplicatedWayToFetchOptions()
            $this->setOptions($options);
        }
        return parent::getOptions();
    }

Looks good. But because author was accessing private fields whenever he felt like doing so – you have more work to do. You also have to fix getOption($code) as well.

    public function getCustomOption($code)
    {
        return $this->getCustomOptions()[$code]?: null;
    }

I think it would be a good rule for PHP code that there’s one and only one method which access private fields directly. Even if rules of OOP allows you to access private field – it’s most definitely bad idea to do so. If you need no public getter – make private one.

It would be a simple way to keep “hygene” of your code. Do you agree?

Share Button