首页 >后端开发 >php教程 >php访问控制(public protected private)

php访问控制(public protected private)

WBOY
WBOY原创
2016-08-08 09:19:151167浏览

在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教程有兴趣的朋友有所帮助。

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn