PHP后期静态绑定概念和用法

1,117 阅读1分钟

PHP后期静态概念

PHP后期静态绑定(late static binding)是指在继承范围内引用静态调用类的技术

也就是,在类的继承过程中,使用的类不再是当前类,而是调用的类。后期静态绑定使用关键字static来实现,static::不再被解析为定义当前方法所在的类,而是运行时最初调用的类。

用法

1. 静态方法调用

class A {
    public static function call() {
        echo 'class A';
    }
    
    public static function test() {
        self::call();//当前类
        static::call();//调用的类,static是根据调用test()函数的类来决定static::的值
    }
}

class B extends A {
    public static function call() {
        echo 'class B';
    }
}

B::test();
//输出为:
// class A
// class B

2. 实例方法调用

class A {
    public function call() {
        echo 'install from A';
    }
    
    public function test() {
        self::call();
        static::call();
    }
}

class B extends A {
   public function call() {
       echo 'instance from B';
   }
}

$b = new B();
$b->test();
/****输出***/
// instance from A
// instance from B

3. 实例化对象

class A {
    public static function create() {
        $self = new self();
        $static = new static();
        return [$self, $static];
    }
}

class B extends A {
    
}

$arr = B::create();
foreach($arr as $value) {
    var_dump($value);
}

/****输出***/
// object(A)[1]
// object(B)[2]