Access control of attributes or methods in php is achieved by adding keywords such as public private protected in front. Public-modified class members can be accessed anywhere, private-modified class members can only be accessed by themselves, protected Modified class members can be accessed by itself or its subclasses.
<code><span><span><?php</span><span><span>class</span><span>test</span>{</span><span>public</span><span>$public</span>=<span>'public'</span>; <span>private</span><span>$private</span>=<span>'private'</span>; <span>protected</span><span>$protected</span>=<span>'protected'</span>; <span>public</span><span><span>function</span><span>show</span><span>()</span>{</span><span>echo</span><span>$this</span>-><span>private</span>; } <span>public</span><span><span>function</span><span>show2</span><span>()</span>{</span><span>echo</span><span>$this</span>-><span>protected</span>; } } <span>$test</span>=<span>new</span> test(); <span>echo</span><span>$test</span>-><span>public</span>; <span>$test</span>->show(); <span>$test</span>->show2(); <span>// exit();</span><span>// echo $test->protected; //会产生一个致命错误</span><span>// echo $test->private; //也会产生一个致命错误 private属性只能在定义的类中访问</span><span>/** * */</span><span><span>class</span><span>test2</span><span>extends</span><span>test</span> {</span><span>//重写父类的show()方法</span><span><span>function</span><span>show</span><span>()</span>{</span><span>//继承自父类的protected</span><span>echo</span><span>$this</span>-><span>protected</span>; } } <span>$test2</span>=<span>new</span> test2(); <span>echo</span><span>"<hr/>"</span>; <span>// $test2->protected; //会产生一个致命错误 protected属性不能在外部访问</span><span>$test2</span>->show(); <span>//能够访问 protected只能被自身或其子类访问</span><span>?></span></span></span></code>
Copyright Statement: This article is an original article by the blogger and may not be reproduced without the blogger's permission.
The above introduces PHP access control (public protected private), including aspects of the content. I hope it will be helpful to friends who are interested in PHP tutorials.