/**
* php类常量
*
* 类常量属于类自身,不属于对象实例,不能通过对象实例访问
* 不能用public,protected,private,static修饰
* 子类可以重写父类中的常量,可以通过(parent::)来调用父类中的常量
* 自php5.3.0起,可以用一个变量来动态调用类。但该变量的值不能为关键字(如self,parent或static)。
*/
class foo
{
// 常量值只能是标量,string,bool,integer,float,null,可以用nowdoc结构来初始化常量
const bar = 'bar';
public static function getconstantvalue()
{
// 在类的内部可以用self或类名来访问自身的常量,外部需要用类名
return self::bar;
}
public function getconstant()
{
return self::bar;
}
}
$foo = 'foo';
echo $foo::bar, '
';
echo foo::bar, '
';
$obj = new foo();
echo $obj->getconstant(), '
';
echo $obj->getconstantvalue(), '
';
echo foo::getconstantvalue();
// 以上均输出bar
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
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号