php面向对象之访问权限修饰符

来源:互联网 发布:大陆悬疑推理网络剧 编辑:程序博客网 时间:2024/06/07 02:50
PHP中有三种访问修饰符,分别是:
     public(公共的、默认)
     protected(受保护的)
     private(私有的)
public(公共的、默认)在PHP5中如果类没有指定成员的访问修饰符,默认就是public的访问权限。
protected(受保护的)被声明为protected的成员,只允许该类的子类进行访问。
private(私有的 ) 被定义为private的成员,对于类内部所有成员都可见,没有访问限制。对类外部不允许访问。
 
图解


多的不说,上代码

<?phpclass person {    public $name;    protected $age;    private $secret;    public function __construct($name, $age, $secret)    {        $this->name = $name;        $this->age = $age;        $this->secret = $secret;    }    public function sayMyInfo1()    {        printf("my name's %s, age's %d, secret's %s", $this->name, $this->age, $this->secret);    }}class student extends person {    public function sayMyInfo2()    {        printf("my name's %s, age's %d, secret's %s", $this->name, $this->age, $this->secret);    }}$p = new person('炎帝', 32, '尝百草');echo $p->name;  //炎帝echo $p->age; //fatal错误 不能访问私有属性echo $p->secret; //fatal错误 不能访问私有属性$p->sayMyInfo1(); //my name's 炎帝, age's 32, secret's 尝百草echo "<hr />";$s = new student('lightWay', 23, '大明湖畔');echo $s->name;  //lightWayecho $s->age; //fatal错误 不能访问私有属性echo $s->secret; //notice错误 没有定义$s->sayMyInfo2(); //my name's lightWay, age's 23, secret's ### 这里会产生一个notice级别错误 没有定义 ###


0 0
原创粉丝点击