You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
72 lines
1.8 KiB
72 lines
1.8 KiB
<?php
|
|
/*
|
|
* @Author: your name
|
|
* @Date: 2022-03-12 15:09:52
|
|
* @LastEditTime: 2022-03-14 10:35:02
|
|
* @LastEditors: Please set LastEditors
|
|
* @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
|
|
* @FilePath: /wiggins/myDemo/php_demo/07面向对象/12-类常量.php
|
|
*/
|
|
/**
|
|
* 类里面的常量
|
|
* 类常量不属于类的属性,与类属性等级并列
|
|
* 类属于类本身,不属于对象,不能通过‘->'访问
|
|
* 子类可以重写父类的类常量,通过区域解析符(parent::)调用父类中的类常量
|
|
*/
|
|
|
|
class ClassA
|
|
{
|
|
//定义类常量
|
|
const a='这是一个类常量';
|
|
|
|
function func()
|
|
{
|
|
//在类的方法中调用本类常量
|
|
echo self::a.PHP_EOL;
|
|
}
|
|
}
|
|
|
|
//直接调用类常量
|
|
echo ClassA::a.PHP_EOL;
|
|
|
|
//对象::类常量,PHP5.3起可以使用变量调用类常量
|
|
$obj = new ClassA();
|
|
echo $obj::a.PHP_EOL;
|
|
//echo $obj->a.'<br>'; //对象不能访问类常量,会报“Undefined property: ClassA::$a”
|
|
|
|
//对象中方法调用类常量
|
|
$obj->func();
|
|
|
|
|
|
//访问父类类常量
|
|
class ClassB extends ClassA
|
|
{
|
|
function func(){
|
|
echo parent::a.PHP_EOL;
|
|
}
|
|
}
|
|
|
|
echo "调用父类的类常量".PHP_EOL;
|
|
$obj=new ClassB();
|
|
$obj->func();
|
|
|
|
|
|
//重写父类的类常量
|
|
class ClassC extends ClassA
|
|
{
|
|
const a = "这个一个被子类重写的类常量";
|
|
|
|
function func(){
|
|
echo parent::a.PHP_EOL;
|
|
}
|
|
|
|
}
|
|
|
|
echo ClassC::a.PHP_EOL; //被子类重写的类常量
|
|
$obj=new ClassB(); //这是一个类常量
|
|
$obj->func();
|
|
|
|
/**
|
|
* 感悟:类常量估计是在编译时已经实例化在内存的东西,所以不能再实例化
|
|
*/
|
|
?>
|