《PHP教程:php面向对象编程self和static的区别》要点:
本文介绍了PHP教程:php面向对象编程self和static的区别,希望对您有用。如果有疑问,可以联系我们。
在php的面向对象编程中,总会遇到PHP学习
class test{
public static function test(){
self::func();
static::func();
}
public static function func(){}
}
可你知道self和static的区别么?PHP学习
其实区别很简单,只需要写几个demo就能懂:PHP学习
Demo for self:
PHP学习
class Car
{
public static function model(){
self::getModel();
}
protected static function getModel(){
echo "This is a car model";
}
}
Car::model();PHP学习
Class Taxi extends Car
{
protected static function getModel(){
echo "This is a Taxi model";
}
}
Taxi::model();
得到输出PHP学习
This is a car model This is a car model
可以发现,self在子类中还是会调用父类的办法PHP学习
Demo for static
PHP学习
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();
得到输出PHP学习
This is a car model This is a Taxi model
可以看到,在调用static,子类哪怕调用的是父类的办法,但是父类办法中调用的办法还会是子类的办法(好绕嘴..)PHP学习
在PHP5.3版本以前,static和self还是有一点区别,具体是什么,毕竟都是7版本的天下了.就不去了解了.PHP学习
总结呢就是:self只能引用当前类中的办法,而static关键字允许函数能够在运行时动态绑定类中的办法.PHP学习
转载请注明本页网址:
http://www.vephp.com/jiaocheng/6757.html