php面向对象编程self和static的区别
在php的面向对象编程中,总会遇到
classtest{
publicstaticfunctiontest(){
self::func();
static::func();
}
publicstaticfunctionfunc(){}
}
可你知道self和static的区别么?
其实区别很简单,只需要写几个demo就能懂:
Demoforself:
classCar
{
publicstaticfunctionmodel(){
self::getModel();
}
protectedstaticfunctiongetModel(){
echo"Thisisacarmodel";
}
}
Car::model();
ClassTaxiextendsCar
{
protectedstaticfunctiongetModel(){
echo"ThisisaTaximodel";
}
}
Taxi::model();
得到输出
Thisisacarmodel Thisisacarmodel
可以发现,self在子类中还是会调用父类的方法
Demoforstatic
classCar
{
publicstaticfunctionmodel(){
static::getModel();
}
protectedstaticfunctiongetModel(){
echo"Thisisacarmodel";
}
}
Car::model();
ClassTaxiextendsCar
{
protectedstaticfunctiongetModel(){
echo"ThisisaTaximodel";
}
}
Taxi::model();
得到输出
Thisisacarmodel ThisisaTaximodel
可以看到,在调用static,子类哪怕调用的是父类的方法,但是父类方法中调用的方法还会是子类的方法(好绕嘴。。)
在PHP5.3版本以前,static和self还是有一点区别,具体是什么,毕竟都是7版本的天下了。就不去了解了。
总结呢就是:self只能引用当前类中的方法,而static关键字允许函数能够在运行时动态绑定类中的方法。
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下