用法类似与 self,static::不再被解析为定义当前方法所在的类,而是再实际运行时计算的。比如当一个子类继承了父类的静态属性或方法的时候,它的值并不能被改变,有时不希望看到这种情况。
问题:
当一个子类继承了父类的静态属性或方法的时候,它的值并不能被改变
<?php
class Person
{
static $name = 'lucy';
const AGE = 22;
public static function intro()
{
echo 'My name is ' . self::$name . '<br>';
echo 'My age is ' . self::AGE . '<br>';
}
}
class Stu extends Person
{
static $name = 'bob';//无法被调用
}
Person::intro();//My name is lucy //My age is 22
Stu::intro();//My name is lucy //My age is 22
解法一:重写(但是代码很繁琐)
<?php
class Person
{
static $name = 'lucy';
const AGE = 22;
public static function intro()
{
echo 'My name is ' . self::$name . '<br>';
echo 'My age is ' . self::AGE . '<br>';
}
}
class Stu extends Person
{
static $name = 'bob';//无法被调用
public static function intro()
{
echo 'My name is ' . self::$name . '<br>';
echo 'My age is ' . self::AGE . '<br>';
}
}
Person::intro();//My name is lucy //My age is 22
Stu::intro();//My name is bob //My age is 22
解法二:(延迟绑定)
<?php
class Person
{
static $name = 'lucy';
const AGE = 22;
//延迟绑定函数
public static function intro1()
{
echo 'My name is ' . static::$name . '<br>';
echo 'My age is ' . static::AGE . '<br>';
}
}
class Stu extends Person
{
static $name = 'bob';//无法被调用
}
Person::intro1();//My name is lucy //My age is 22
Stu::intro1();//My name is bob //My age is 22