客官,留下你的赞;成为我的粉丝,一起上车哦!评论区欢迎你的留言
GitHub代码案例下载
PHP类常量和接口常量的区别
两者的使用上是一样的,只是接口常量不能被子类或者子接口覆盖
。
PHP类常量的使用
父类和子类可定义名称一样的常量,两者相互不影响
<?php
/**
* PHP类常量
* @author new1024kb
* @since 2019-12-23
*/
//父类
class Student {
const NAME = 'new1024kb';
}
echo Student::NAME; //输出:new2014kb
//子类
class Sunny extends Student {
const NAME = 'sunny new1024kb';
}
echo Sunny::NAME; //输出:sunny new1024kb
接口常量的使用
输出接口中的常量
<?php
/**
* PHP接口常量
* @author new1024kb
* @since 2019-12-23
*/
interface Student {
const NAME = 'new1024kb';
}
echo Student::NAME; //输出1024kb
implements
实现接口(‘子类’不能覆盖接口中的常量
)
<?php
/**
* PHP接口常量
* @author new1024kb
* @since 2019-12-23
*/
interface Student {
const NAME = 'new1024kb';
}
//Sunny类实现Student接口
class Sunny implements Student {
const NAME = 'sunny new1024kb';
}
/**
* 报错信息:
* Fatal error: Cannot inherit previously-inherited
* or override constant NAME from interface Student
*/
extends
继承父类接口,子类接口不能覆盖父类接口中的常量
<?php
/**
* PHP接口常量
* @author new1024kb
* @since 2019-12-23
*/
interface Student {
const NAME = 'new1024kb';
}
//子接口Monitor继承父接口Student
interface Monitor extends Student {
const NAME = 'monitor new1024kb';
}
/**
* 报错信息:
* Fatal error: Cannot inherit previously-inherited
* or override constant NAME from interface Student
*/