Home > Backend Development > PHP Tutorial > php类对象中__get()和__set()方法使用教程

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

WBOY
Release: 2016-06-20 13:03:44
Original
1048 people have browsed it

问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>
Copy after login

求解释,为啥输出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>
Copy after login

答:这里输出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>
Copy after login

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

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


source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template