php中 new self 和 new static的区别

使用self::或者_class_对当前类的静态引用,取决于当前类,指的是当前类.

static和this很像,不再是指代当前类,在运行时,指代的运行的那个类,而static还可以用于静态方法和属性,这种方式又叫后期静态绑定

看个例子:

class father
{
    public static function name()
    {
        echo "A";
    }
    public static function callself()
    {
        self::name();
    }

    public static function callstatic()
    {
        static::name();
    }
}

class son extends father
{
    public static function name()
    {
        echo "B";
    }
}
son::name();        // output: B
son::callself();    // output: A
son::callstatic();  // output: B  

子类son,callstatic()函数调用的是自己name方法,而callself()函数调用的是父类的name()方法

也就是只有在继承的时候,体现出了self和statis的不同,self实例化永远指向本类,而statis没有继承关系时和statis一样都是指向本类,但是在子类中使用statis和this的作用就一样,指向的是运行中的类, 

所以又叫后期静态绑定 

还有一点就是,static并不限于静态方法的调用,同样适用于费静态函数的调用

原文地址:https://www.cnblogs.com/hanshuai0921/p/6698885.html