PHP 无法访问受保护的属性错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6307107/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 23:56:27  来源:igfitidea点击:

PHP cannot access protected property error

php

提问by Ram

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

PHP 致命错误:无法访问第 23 行 /web/index.php 中的受保护属性 Exception::$message

On line 23 I have,

在第 23 行,我有,

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?

我看不出这有什么问题,但我偶尔会在日志中看到上述异常。怎么了?

回答by Karl-Bj?rnar ?ie

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

使用$e->getMessage()而不是$e->message因为消息是受保护的属性:)

回答by meagar

$messageis a protectedmember of class Exception, as the error message states. You want the public accessor getMessage:

$message是异常类的受保护成员,如错误消息所述。您需要公共访问器getMessage

$e->getMessage()

回答by RaviRokkam

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

声明为 protected 的成员只能在类本身内以及被继承类和父类访问。

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 Visibilityhere

您可以在此处深入了解属性可见性