简体   繁体   English

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

[英]Child class access to private member variables in the parent class

I try to create class User and Teacher extends from User class I have a problem with the Teacher class can access to private member variables in the parent class it's weird.我尝试创建 class UserTeacherUser class 扩展 我对Teacher有问题 class 可以访问parent ZA2F21ED4F8EBC2BBB1它的奇怪成员变量。

User Class User Class

<?php

class User
{
    private $username;

    protected $password;

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

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

Teacher Class 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 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 科技

Windows 10 Windows 10

Any logical reason?有什么合乎逻辑的理由吗?

$this->username does not call parent private member username , it creates new child object property username dynamically. $this->username不调用父私有成员username ,它动态创建新的子 object 属性username

To keep username private in Teacher, you need to set field as protected.要在教师中保持username私有,您需要将字段设置为受保护。 Protected fields means that is private for super class and also for children.受保护的字段意味着对于超级 class 和儿童来说是私有的。

You can not access private properties or methods of class from outside of it.您不能从外部访问 class 的私有属性或方法。

Teacher::$username is an undefined property in this case (1. private property of parent is invisible for it's childs 2. it is not defined in itself), so whenever you call getUsername() a notice is thrown and depending on your error reporting config you'll see this on screen or not. Teacher::$username在这种情况下是一个未定义的属性(1. 父级的私有属性对于它的子级是不可见的 2. 它本身没有定义),所以每当你调用getUsername()时,都会抛出一个通知,具体取决于你的错误报告配置你会在屏幕上看到这个。

If you want to acces User::$username from Teacher class, you have to make it protected or public- what's the difference: check this for more informations https://www.php.net/manual/en/language.oop5.visibility.php如果您想从Teacher class 访问User::$username ,您必须将其设为受保护或公开 - 有什么区别:查看此以获取更多信息https://www.php.net/manual/en/language.oop5。能见度.php

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM