我尝试创建类User
,并且Teacher
从User
类扩展
我有一个Teacher
类问题,可以访问parent
类中的 private 成员变量,这很奇怪。
User
类
<?php
class User
{
private $username;
protected $password;
public function login()
{
return 'login';
}
public function register()
{
return 'register';
}
}
Teacher
类
<?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)(内置:2019年1月9日22:23:26)(ZTS MSVC15(Visual C ++ 2017)x64) 版权所有(c)1997-2018 The PHP Group Zend Engine v3.2.0,版权所有(c)1998-2018 Zend Technologies
Windows 10
任何合乎逻辑的理由吗?
答案 0 :(得分:2)
$this->username
不会调用父私有成员username
,而是动态创建新的子对象属性username
。
要在“教师”中将username
设为私有,您需要将字段设置为受保护。受保护的字段意味着对于超级班级和孩子来说都是私有的。
答案 1 :(得分:-1)
您不能从外部访问私有属性或类的方法。
在这种情况下, Teacher::$username
是一个未定义的属性(1. parent的私有属性对于它的孩子是不可见的2.它本身未定义),因此,每当您调用getUsername()
时都会引发通知并且根据您的错误报告配置,您是否会在屏幕上看到它。
如果您想从User::$username
类访问Teacher
,则必须将其设置为受保护或公开-有什么区别:请查看此以获取更多信息
https://www.php.net/manual/en/language.oop5.visibility.php