开发者

PHP cannot access protected property error

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

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-respo开发者_如何转开发nse status="error">
<message><![CDATA['.$e->message.']]></message>
</error-response>';


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


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

$e->getMessage()


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜