在php中對屬性或方法的存取控制,是在前面加public private protected等關鍵字來實現的,public修飾的類別成員可以在任何地方存取,private修飾的類別成員只能夠被自身訪問,protected修飾的類別成員能被自身或其子類別存取。
<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>
版權聲明:本文為部落客原創文章,未經部落客允許不得轉載。
以上就介紹了php存取控制(public protected private),包含了方面的內容,希望對PHP教程有興趣的朋友有所幫助。