<?php class Foo { const BAR = 'bar'; public static function getConstantValue() { return self::BAR; } public function getConstant() { return self::BAR; } } $foo = 'Foo'; echo $foo::BAR, '<br />'; echo Foo::BAR, '<br />'; $obj = new Foo(); echo $obj->getConstant(), '<br />'; echo $obj->getConstantValue(), '<br />'; echo Foo::getConstantValue(); class Bar extends Foo { const BAR = 'foo'; public static function getMyConstant() { return self::BAR; } public static function getParentConstant() { return parent::BAR; } } echo Bar::getMyConstant(); // foo echo Bar::getParentConstant(); // bar
类常量属于类自身,不属于对象实例,不能通过对象实例访问
不能用public,protected,private,static修饰
子类可以重写父类中的常量,可以通过(parent::)来调用父类中的常量
自PHP5.3.0起,可以用一个变量来动态调用类。但该变量的值不能为关键字
申明:本站所有资源都是转载各大下载站,或由网友投稿发布,请自行检测软件的完整性,如有侵权请联系我们删除下架,联系方式:admin@php.cn