旗肝淖蹲犁派抵怖髓盆念唱痕
细说static
一、用途:
1.类中声明静态成员
2.函数中声明静态变量
3.后期静态绑定
二、特点:
1.静态成员属于类,必须用类访问
2.静态方法比较特殊,允许用对象访问,但不推荐
3.必须使用范围解析符::访问,不允许使用对象访问符->访问
4.静态属性仅允许使用字面量(字符/数值/数组)或常量进行初始化(禁止表达式/变量/对象)
三、后期静态绑定/延迟静态绑定
注:php.net官网上有介绍非常的晦涩难懂,这里做一个简化说明
1. 转发调用是什么?
答:说人话,就是以回调的方式来执行静态方法,用回调就必须指定调用者或代理函数。
调用者可以是self,parent,static
代理函数有很多:
forward_static_call(callable,arg1…)
forward_static_call_array(callable,array)
call_user_func(callable,arg1…)
call_user_func_array(callable,array)
新建demo5.php
<?php class Demo1 { public static function test1() { return implode(',',func_get_args());//将数组用逗号分割为字符串 } //后期静态绑定(延迟静态绑定) public static function test3() { return self::test1('php','mysql','thinkphp'); } } class Demo2 extends Demo1 { //重写test1() public static function test1() { return __METHOD__; } public static function test2() { //1.传统调用父类的静态方法 return parent::test1('hello','萌面人资料铺'); } } //调用Demo2::test2(); echo Demo2::test2(); echo "<hr>"; //调用Demo2::test3(); echo Demo2::test3();
执行:
分析
1. test3()方法在Demo1类中
2. Demo2类继承自Demo1,所以可以用Demo2访问test3()
3. test3()中访问了当前类的test1()方法,当然是Demo1类的test1()
4. 但是我是用Demo2类调用的test3(),因此我的本意,肯定是想调用Demo2中重载的test1()
5. 那么,如果能让当前静态方法的调用者,根据继承关系的上下文自动进行判断呢?
6. 在静态方法前使用static关键字,这样就可以自动判断是哪个类在调用我了~~
7. 运行时会自动将static,替换成Demo2类
static关键字:自动识别调用的类 如果是Demo1在调用就调用Demo1的test1()
如果调用者是Demo2 则自动调用Demo2的test1()方法
<?php class Demo1 { public static function test1() { return implode(',',func_get_args());//将数组用逗号分割为字符串 } //后期静态绑定(延迟静态绑定) public static function test3() { // return self::test1('php','mysql','thinkphp'); //static关键字:自动识别调用的类 如果是Demo1在调用就调用Demo1的test1() //如果调用者是Demo2 则自动调用Demo2的test1()方法 //类方法的调用者,在声明时指定,是前期调用,在编译阶段完成 //类方法的调用者,在执行时指定,是后期调用,在运行阶段完成 return static::test1('php','mysql','thinkphp'); } } class Demo2 extends Demo1 { //重写test1() public static function test1() { return __METHOD__; } public static function test2() { //1.传统调用父类的静态方法 return parent::test1('hello','萌面人资料铺'); } } //调用Demo2::test2(); echo Demo2::test2(); echo "<hr>"; //调用Demo2::test3(); echo Demo2::test3();
执行,可以看见echo Demo2::test3();调用了Demo2的test1()方法:
潘惺懈史加疮扭沉饲粒琅纷唇