子 class 访问父 class 中的私有成员变量

Child class access to private member variables in the parent class

我尝试创建 class User 并且 TeacherUser class 扩展 我有一个问题 Teacher class 可以访问 private 成员变量 parent class 这很奇怪。

User Class

<?php

class User
{
    private $username;

    protected $password;

    public function login()
    {
        return 'login';
    }

    public function register()
    {
        return 'register';
    }
}

Teacher Class

<?php
class Teacher extends User
{
    public $id;

    public $name;

    public $description;

    public $email;

    public $phone;


    public function getUsername()
    {
        return $this->username;
    }


    public function getPassword()
    {
        return $this->password;
    }
}

PHP 7.2.14 (cli) (built: Jan 9 2019 22:23:26) ( ZTS MSVC15 (Visual C++ 2017) x64 ) Copyright (c) 1997-2018 The PHP Group Zend Engine v3.2.0, Copyright (c) 1998-2018 Zend Technologies

Windows 10

有什么合乎逻辑的原因吗?

$this->username 不调用父私有成员 username,它动态创建新的子对象 属性 username

要在 Teacher 中保持 username 私有,您需要将字段设置为受保护。受保护的字段意味着超级 class 和儿童也是私有的。

您无法从外部访问 class 的私有属性或方法。

Teacher::$username 在这种情况下是一个未定义的 属性(1. parent 的 private 属性 对于它的 childs 是不可见的 2. 它本身没有定义),所以每当你调用 getUsername() 会抛出一条通知,根据您的错误报告配置,您是否会在屏幕上看到它。

如果您想从 Teacher class 访问 User::$username,您必须将其设置为受保护或 public- 有什么区别:查看此以获取更多信息 https://www.php.net/manual/en/language.oop5.visibility.php