PHP中const,static,public,private,protected的区别

原文地址:http://small.aiweimeng.top/index.php/archives/54.htmlphp

const: 定义常量,通常定义后不可改变
static: 静态,类名能够访问
public: 表示全局,类内部外部子类均可以访问;
private: 表示私有的,只有本类内部可使用;
protected: 表示受保护的,只有本类或子类或父类中能够访问;html

定义常量也可用```define```定义。函数

const与define在定义常量时会有以下区别:this

1. const用于类成员变量,一经定义不可修改,define用于全局常量,不可用于类成员变量的定义,
const可在类中使用,define不能。
2. const定义的常量大小写敏感,而define可经过第三个参数(为TRUE表示大小写不敏感)来指定大小写是否敏感。
在运行时定义一个常量。define('TXE',100,TRUE);
3. const不能在条件语句中定义常量,而define函数能够。if($a>10){define('LE','hello');}htm

class Demo
{

    //定义常量【自php5.3后】,一个常量是属于一个类的,而不是某个对象的
    //不可改变的
    const EVENT = 'const';

    static $event = 'static';

    public $eventPublic = 'public';

    private $eventPrivate = 'private';

    protected $eventProtected = 'protected';


    public function test()
    {
        //使用self访问类中定义的常量
        echo self::EVENT.'<br/>';

        //同常量同样使用self
        echo self::$event.'<br/>';

        //公共变量,受保护的变量,私密的变量经过$this访问
        echo $this->eventPublic.'<br/>';

        //受保护的和私密的变量只能在当前类中访问
        echo $this->eventPrivate.'<br/>';
        echo $this->eventProtected.'<br/>';
    }


    //魔术方法
    public function __get($name)
    {
        return $this->$name;
    }

}


class One extends Demo
{

    public function testOne()
    {
        //可继承父级使用parent访问
        echo parent::EVENT.'<br/>';
        echo parent::$event.'<br/>';

        //也可经过父类直接访问
        echo Demo::EVENT.'<br/>';
        echo Demo::$event.'<br/>';

        //继承父级中的成员变量后,只能访问公共变量
        //私有变量和受保护的变量不能在子类中访问
        echo $this->eventPublic;

    }

}
$obj_1 = new Demo;
$obj_1->test();
echo "=================<br/>";
$obj = new One;
$obj->testOne();

  

运行结果:对象

const
static
public
private
protected
=================
const
static
const
static
public