PHP 面向对象 static 和 self 的区别

本文通过两个实例对比self::method与static::method在PHP面向对象编程中的使用区别。self::method不会被子类覆盖,而static::method则可以被子类重写。

一、前言

php是世界上最好的语言

php从面向过程走到现在成熟的面向对象体系, 在php面向对象中,静态变量的调用我们可以用这两个self::method和 static::method, 但是很多童鞋迷惑,不理解self::method和static::method有什么区别,下面给出两个例子一看究竟:

例子1:

 1 class Car {
 2     public static function model()
 3     {
 4         self::getModel();
 5     }
 6     protected static function getModel()
 7     {
 8         echo "This is a car model";
 9     }
10 }
11 Car::model(); //This is a car model
12 echo '<br />';
13 Class Taxi extends Car {
14     protected static function getModel()
15     {
16         echo "This is a Taxi model";
17     }
18 }
19 Taxi::model(); //This is a car model

总结: self::getModel()调用方法getModel(), 子类的方法getModel()实际意义上没有重载父类的方法getModel().

例子2 :

 

 1 class Car {
 2     public static function model()
 3     {
 4         static::getModel();
 5     }
 6     protected static function getModel()
 7     {
 8         echo "This is a car model";
 9     }
10 }
11 Car::model();  //This is a car model
12 echo '<br />';
13 Class Taxi extends Car {
14     protected static function getModel()
15     {
16         echo "This is a Taxi model";
17     }
18 }
19 Taxi::model(); //This is a Taxi model

 

总结: self::getModel()调用方法getModel(), 子类的方法getModel()重载了父类的方法getModel().

童鞋们,理解了吗?

如有疑惑,欢迎评论

 

转载于:https://www.cnblogs.com/hellow-world/p/9188607.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值