为什么我不能在 PHP 中调用这个受保护的函数


Why can't i call this protected function in PHP?

这可能是

一个基本问题,但我遵循本教程,代码一度看起来像这样。

<?php
class person
{
    public $name;
    public $height;
    protected $social_security_no;
    private $pin_number = 3242;
    public function __construct($person_name)
    {
        $this->name = $person_name;
    }
    public function set_name($new_name)
    {
        $this->name = $new_name;
    }
    protected function get_name()
    {
        return $this->name;
    }
    public function get_pin_number_public()
    {
        $this->pub_pin = $this->get_pin_number();
        return $this->pub_pin;
    }
    private function get_pin_number()
    {
        return $this->pin_number;
    }
}
class employee extends person
{
    public function __construct($person_name)
    {
        $this->name = $person_name;
    }
    protected function get_name()
    {
        return $this->name;
    }
}

但是当我使用它时

<?php include "class_lib.php";?>
    </head>
    <body id="theBody">
    <div>
<?php
$maria = new person("Default");
$dave = new employee("David Knowler");
echo $dave->get_name();
?>

我收到此错误

致命错误:从以下位置调用受保护的方法 employee::get_name(( 上下文 '' 在 C:''Users''danny''Documents''Workspace''test''index.php on 13号线

问题似乎是当我在 employee 类中将 protected 添加到 get_name(( 函数时,但在我看来,这是本教程中的首选覆盖方式。有什么想法吗?

问题不在于您无法覆盖受保护的方法,而在于您从类外部调用受保护的方法。

实例化类后,您可以调用一个公共方法,该方法又可以调用get_name()并且您将看到代码将按预期工作。

例如:

class employee extends person {
    function __construct($person_name){
        $this->name = $person_name;
    }
    protected function get_name() {
        return $this->name;
    }
    public function name()
    {
        return $this->get_name();
    }
}
$dave = new employee("David Knowler");
echo $dave->name();

在您的示例中,您可能最好公开get_name()

"问题似乎在于当我在员工类的get_name()函数中添加protected时" - 这是你的答案。受保护的方法只能从同一个类或子类调用,而不能"从外部"调用。如果要以这种方式使用方法,则必须是公共的。

您可以在人员类或员工类中访问 get_name((,而不是在这两个类之外。

检查受保护的可见性

http://php.net/manual/en/language.oop5.visibility.php