在PHP中,self和static都是关键字,但它们在使用上是有区别的。
self关键字表示当前所在类,可以用来访问当前类的常量、静态变量或静态方法。在方法内部通过self关键字访问静态方法和静态变量时,无法获取到子类中重载该方法或变量的值。示例代码如下:
class ParentClass {
const CONSTANT = 'parent constant';
static $staticVariable = 'parent static variable';
public static function staticFunction() {
echo 'This is parent static function';
}
public static function callSelf() {
echo self::CONSTANT . PHP_EOL;
echo self::$staticVariable . PHP_EOL;
self::staticFunction();
}
}
class ChildClass extends ParentClass {
const CONSTANT = 'child constant';
static $staticVariable = 'child static variable';
public static function staticFunction() {
echo 'This is child static function';
}
}
ParentClass::callSelf();
ChildClass::callSelf();
输出结果为:
parent constant
parent static variable
This is parent static function
child constant
child static variable
This is parent static function
从输出结果可以看出,无论是在父类还是子类中调用`callSelf`方法,都只会输出父类中的常量、静态变量和静态方法,因为在使用self关键字时,它表示的是当前所在的类,而不是调用该方法的对象所属的类。
而static关键字则表示当前所在的类,可以用来访问静态变量和静态方法的时候,会根据实际调用的对象的类型来决定其调用的方法或变量。示例代码如下:
class ParentClass {
const CONSTANT = 'parent constant';
static $staticVariable = 'parent static variable';
public static function staticFunction() {
echo 'This is parent static function';
}
public static function callStatic() {
echo static::CONSTANT . PHP_EOL;
echo static::$staticVariable . PHP_EOL;
static::staticFunction();
}
}
class ChildClass extends ParentClass {
const CONSTANT = 'child constant';
static $staticVariable = 'child static variable';
public static function staticFunction() {
echo 'This is child static function';
}
}
ParentClass::callStatic();
ChildClass::callStatic();
输出结果为:
parent constant
parent static variable
This is parent static function
child constant
child static variable
This is child static function
从输出结果可以看出,无论是在父类还是子类中调用`callStatic`方法,都能根据实际调用的对象的类型来决定其调用的方法或变量。当调用子类中的方法或变量时,会使用子类中的值,而非父类中的值。这就是static和self的区别。
正文完