php中的new self()与new static()

php中的new self()与new static()

看thinkphp代码时发现了一个以前没有见过的方法static()

public static function instance($options = [])
 {
 if (is_null(self::$instance)) {
 self::$instance = new static($options);
 }
 return self::$instance;
 }

查了一下 new static()是php 5.3添加的延迟静态绑定(后期延迟绑定)功能。它和new self()的相同点在于都是用来实例化一个类,但new self()是实例化代码声明时所在的类,而new static()是实例化调用时所在的类。

self refers to the same class whose method the new operation takes place in.

static in PHP 5.3's late static bindings refers to whatever class in the hierarchy which you call the method on.

In the following example, B inherits both methods from A. self is bound to A because it's defined in A's implementation of the first method, whereas static is bound to the called class (also see get_called_class() ).

示例


输出是

object(A)[1]
object(A)[1]
object(A)[1]
object(B)[1]

参考文章

后期静态绑定

PHP中new static()与new self()的区别异同分析

你可能感兴趣的:(php中的new self()与new static())