Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should we access protected properties directly or with getters?

Tags:

php

Should we access protected properties directly or with getters in PHP ?

I have two classes with one is the daughter of the other. In the mother, I declare certain properties as protected and I generate all getters for my properties. So, I can access and define those properties directly or via the getters, but I don't know if there is a better solution.

Example :

class Mother {

    private $privateProperty;
    protected $protectedProperty;
    public $publicProperty;

    /*** Private property accessors ***/   

    public function setPrivateProperty($value)
    {
        $this->privateProperty = $value;
    }

    public function getPrivateProperty()
    {
        return $this->privateProperty;
    }

    /*** Protected property accessors ***/   

    public function setProtectedProperty($value)
    {
        $this->protectedProperty = $value;
    }

    public function getProtectedProperty()
    {
        return $this->protectedProperty;
    }
}

class Child extends Mother {

    public function showProtectedProperty() {
        return $this->getProtectedProperty();   // This way ?
        return $this->protectedProperty;        // Or this way ?
    }

    public function defineProtectedProperty() {
        $this->setProtectedProperty('value');   // This way ?
        $this->protectedProperty = 'value';     // Or this way ?
    }
}

In the example, I know I can't access/set directly the private property, and that it's useless for public properties. But I can use both ways for the protected property. So, are there any standard to use ?

like image 589
Maxime Picard Avatar asked Feb 17 '16 14:02

Maxime Picard


1 Answers

Best encapsulation is accomplished when you indeed use getters and setters also along a class hierarchy. This means: Attributes should be private and getters/setters are protected (if not public).

For example, if you want to log access to certain attributes, want to add a filter method or another check, the whole mechanism would be removed, if you just accessed those attributes in the derived class.

(Of course, there are situations where you would just make attributes public to make code shorter and because you know that the class is really just a data-holder... In that case, however, those attributes would still not be protected but simply public)

like image 165
IceFire Avatar answered Oct 15 '22 08:10

IceFire