Home » Php » PHP cannot access protected property error

PHP cannot access protected property error

Posted by: admin April 23, 2020 Leave a comment

Questions:

PHP Fatal error: Cannot access protected property Exception::$message in /web/index.php on line 23

On line 23 I have,

echo '<?xml version=\'1.0\'?><error-response status="error">
<message><![CDATA['.$e->message.']]></message>
</error-response>';

I can’t see anything wrong with this, but I see the above exception occasionally in the logs. What’s wrong?

How to&Answers:

Use $e->getMessage() instead of $e->message because message is a protected property 🙂

Answer:

$message is a protected member of class Exception, as the error message states. You want the public accessor getMessage:

$e->getMessage()

Answer:

Members declared protected can be accessed only within the class itself and by inherited and parent classes.

class MyClass {
    public $public = 'Public';
    protected $protected = 'Protected';
    private $private = 'Private';

    function printHello()
    {
        echo $this->public;
        echo $this->protected;
        echo $this->private;
    }
}

$obj = new MyClass();
echo $obj->public; // Works
echo $obj->protected; // Fatal Error
echo $obj->private; // Fatal Error
$obj->printHello(); // Shows Public, Protected and Private

You can dig more into Property Visibility here