Home  >  Article  >  Backend Development  >  一个关于父类方法访问子类对象中的公有属性的有关问题

一个关于父类方法访问子类对象中的公有属性的有关问题

WBOY
WBOYOriginal
2016-06-13 12:11:14793browse

一个关于父类方法访问子类对象中的公有属性的问题
如图所示:

------解决思路----------------------
private $_name = '韩'; 是父类私有属性,所以子类不能修改其值。
showName是父类方法,所以把父类的$_name = '韩'; 输出。

把private 改为 protected 或 public就可以了。


------解决思路----------------------
你把 echo '
类:'.get_class($this).',方法:'.__METHOD__;
改成 echo '
类:'. __CLASS__ .',方法:'.__METHOD__;
就可以从结果中看出了

p1=10,_name=康
p1=10,_name=韩
类:Han,方法:Han::showName

虽然 Kong 了继承了 Han 的方法 showName (__METHOD__ 为 Han::showName)
但他依然工作在 Han 类中,那么 $this->_name 就是 Han::_name 并且永远都是
如果 Han::_name 不是私有的,那么 Kong::_name 将会覆盖 Han::_name
但并不是说 $this->_name 访问的是 Kong::_name,而实际上依然是 Han::_name,只不过两个的值相同而已

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn