Blogger Information
Blog 42
fans 0
comment 0
visits 36461
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
类成员的三种访问限制符
庆选的博客
Original
1737 people have browsed it

实例

<?php

class test{
    public $name;
    protected $price;
    private $num;
    public function __construct($name,$price,$num)
    {
        $this->name = $name;
        $this->price = $price;
        $this->num = $num;
    }

    function get(){
        return '价格是:' .$this->price . '数量是:' . $this->num;
    }
}
$test = new test('电脑','2222','222');
echo 'public 可在类外访问:'.$test->name.'<br>';
echo 'protected/private不可在类外访问,只能通过类内方法访问:'.$test->get().'<br>';

class test2  extends test
{
    function getprice(){
        return '价格是:' .$this->price ;
    }

}

$test2 = new test2('电脑','2222','222');
//echo 'public 可在类外访问:'.$test->name.'<br>';
e

运行实例 »

点击 "运行实例" 按钮查看在线实例

总结:

private:只允许同一个类中被访问,其他子类和外部都不允许被访问到

protected:只允许在同一个类和子类中被访问。不允许外部成员访问

public:在文件内访问无限制

Correction status:qualified

Teacher's comments:访问控制类似于作用域
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post