>  기사  >  백엔드 개발  >  php类对象中__get()和__set()方法使用教程

php类对象中__get()和__set()方法使用教程

WBOY
WBOY원래의
2016-06-20 13:03:44978검색

问1:

<p>class Test{</p><p>private $aa=1;</p><p>function __get($proName){return $this->proName;}</p><p>}</p><p>class subTest extends Test{</p><p>private $aa=2;</p><p>}</p><p>$test=new subTest();</p><p>echo $test->aa;</p>

求解释,为啥输出1?

答:当试图从类的外部访问私有属性时,__get方法会被调用,如果它存在的话subTest继承了Test类,并试图重载aa,但是没有__get()方法,当实例化subTest类后访问它的私有属性,由于__get()方法,所以默认将调用父类的__get方法,当然访问的也是父类的aa属性,如果要输出2可以为subTest类添加__get()

追问:那继承父类的方法能不能访问子类的成员属性

<p>class Test{</p><p>protected $aa=1; function __get($proName){return $this->$proName;}</p><p>}</p><p>class subTest extends Test{</p><p>protected $aa=2;</p><p>}</p><p>$test=new subTest();</p><p>echo $test->aa;</p>

答:这里输出2,因为子类覆盖了从父类继承来的属性aa,因为他们都是protected的,所以可以覆盖

追问:

<p>class Test{</p><p>private $aa=1;</p><p>function __get($proName){</p><p>return $this->$proName;</p><p>}</p><p>class subTest extends Test{</p><p>protected $aa=2;</p><p>}</p><p>$test=new subTest();</p><p>echo $test->aa;</p>

答:这次输出1,是因为子类并没有覆盖父类的属性而且没有自己的__get方法,当访问同一个属性时,php默认将其识别为private,也就是以父类的访问限定符为标准,识别private后就会调用__get()方法,所以输出1

对应的__set()是设置属性的值,原理相似。


성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.