Skip to content
PHP Logo

What are the potential drawbacks of using protected properties in PHP objects when trying to access specific information?

When using protected properties in PHP objects, accessing specific information outside of the class can be challenging as these properties are not directly accessible. One way to solve this issue is by creating getter methods within the class that allow external access to the protected properties.

php
class MyClass {
    protected $myProperty;

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

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

$obj = new MyClass("Hello");
echo $obj->getMyProperty(); // Output: Hello