php - 为什么我不能在PHP中调用此 protected 函数?

标签 php class protected

这可能是一个基本问题,但是我会按照本教程进行操作,并且在某一时刻代码看起来像这样。

<?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();
?>

我得到这个错误

Fatal error: Call to protected method employee::get_name() from context '' in C:\Users\danny\Documents\Workspace\test\index.php on line 13



问题似乎是当我在雇员类的get_name()函数中添加保护时,但是在我看来,这是本教程中重写的首选方法。有任何想法吗?

最佳答案

“问题似乎出在我将protected添加到雇员类的get_name()函数中时” –这就是您的答案。 protected 方法只能从完全相同的类或子类中调用,而不能“从外部”调用。如果要以这种方式使用它,则该方法必须是公开的。

关于php - 为什么我不能在PHP中调用此 protected 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19276734/

相关文章:

php - Ubuntu 的 DNS 缓存存储在哪里?

php - <输入类型="file"接受="image/*;capture=camera">使用php将图像保存到数据库

class - Haskell 自定义数学类型和类

android - public onCreate() 还是 protected onCreate()?

global-variables - Fortran 中 protected 全局变量

php - Wordpress 插件添加页面前端

java - 在 Java 中的同一类的另一个方法中使用一个方法

c++ - 如何跟踪通话统计? C++

c# - 为从 `this` 类型派生的类型提供扩展方法

php上传文件唯一名称问题