Skip to content
PHP Logo

What are the potential pitfalls of using protected properties in PHP classes?

Protected properties in PHP classes can still be accessed and modified by subclasses, potentially leading to unexpected behavior or misuse. To prevent this, consider making use of getter and setter methods to control access to these properties and enforce encapsulation.

php
class MyClass {
    protected $myProperty;

    public function getMyProperty() {
        return $this->myProperty;
    }

    public function setMyProperty($value) {
        $this->myProperty = $value;
    }
}