php类中self和static的区别
全文约 214 字预计阅读 1 分钟
温习php类中static和self的不同
Demo for self:
class Car
{
public static function model(){
self::getModel();
}
protected static function getModel(){
echo "This is a car model";
}
}
Car::model();
Class Taxi extends Car
{
protected static function getModel(){
echo "This is a Taxi model";
}
}
Taxi::model();
输出
This is a car model This is a car model可以发现,self在子类中还是会调用父类的方法
Demo for static
class Car
{
public static function model(){
static::getModel();
}
protected static function getModel(){
echo "This is a car model";
}
}
Car::model();
Class Taxi extends Car
{
protected static function getModel(){
echo "This is a Taxi model";
}
}
Taxi::model();
输出
This is a car model This is a Taxi model可以看到,在调用
static,子类哪怕调用的是父类的方法,但是父类方法中调用的方法还会是子类的方法。
总结呢就是:self只能引用当前类中的方法,而static关键字允许函数能够在运行时动态绑定类中的方法。php类中self和static的区别
评论 0 条
暂无评论,来说点什么吧。