美文网首页
PHP中new static()与new self()以及sel

PHP中new static()与new self()以及sel

作者: 盘木 | 来源:发表于2018-03-19 16:57 被阅读0次

self与static的区别

self - 就是这个类,是代码段里面的这个类。

static - PHP 5.3加进来的只得是当前这个类,有点像$this的意思,从堆内存中提取出来,访问的是当前实例化的那个类,那么 static 代表的就是那个类。

代码示例:

class A {

  public static function get_self() {

    return new self();

  }

  public static function get_static() {

    return new static();

  }

}

class B extends A {}

echo get_class(B::get_self()); // A

echo get_class(B::get_static()); // B

echo get_class(A::get_static()); // A

self调用的就是本身代码片段这个类,而static调用的是从堆内存中提取出来,访问的是当前实例化的那个类,那么 static 代表的就是那个类,下面的例子比较容易明白些。

class A{

    protected static $str="This is A";

    public static function get_info(){

        echo self::$str;

    }

}

class B extends A{

    protected static $str = "This is B";

}

B::get_info();//This is A

class Ao{

    protected static $str="This is Ao";

    public static function get_info(){

        echo static::$str;

    }

}

class Bo extends Ao{

    protected static $str = "This is Bo";

}

Bo::get_info();//This is Bo

总结 其实static就是调用的当前调用的类

相关文章

网友评论

      本文标题:PHP中new static()与new self()以及sel

      本文链接:https://www.haomeiwen.com/subject/iwypqftx.html