zoukankan      html  css  js  c++  java
  • 对比 PHP 中 new static() 与 new self()

    通过new static()与new self()都能产生实例对象,new static()是在PHP5.3版本中引入的新特性,本文对二者稍作对比。

    一、当直接通过本类创建实例时

    class Test
    {
        public static function getIns()
        {
            $obj1 = new self();
            $obj2 = new static();
            return [$obj1, $obj2];
        }
    }
    $arr = Test::getIns();
    var_dump(get_class($arr[0]) === get_class($arr[1])); // true

    通过以上代码可知,当直接从同一个类创建对象时,二者相同。

    二、当子类继承父类创建对象时

    class Test
    {
        public static function getIns()
        {
            $obj1 = new self();
            $obj2 = new static();
            return [$obj1, $obj2];
        }
    }
    class Test1 extends Test
    {
        
    }
    class Test2 extends Test
    {
    
    }
    $arr1 = Test1::getIns();
    echo 'Test1类继承Test类通过self产生实例的类名: ', get_class($arr1[0]), '<br>';    // Test
    echo 'Test1类继承Test类通过static产生实例的类名: ', get_class($arr1[1]), '<hr>';  // Test1
    $arr2 = Test2::getIns();
    echo 'Test2类继承Test类通过self产生实例的类名: ', get_class($arr2[0]), '<br>';    // Test
    echo 'Test2类继承Test类通过static产生实例的类名: ', get_class($arr2[1]);          // Test2

    通过以上代码可知,当子类继承父类的情况下,self与static有所不同: 

    1、new self() 无论是子类还是父类谁调用,都指向被定义时它所在的类。

    2、new static() 则由调用者决定,哪个类调用就指向哪个类。

    总结:通过对比可知,new self() 与 new static() 区别在于是否继承,如果没胡继承则二者效果相同,如果有继承,则self仍指向被定义时的类,而static则指向调用者的类。

  • 相关阅读:
    使用jQuery简单实现产品展示的图片左右滚动功能
    分布式缓存 memcache学习
    js打印html中的内容
    lucene 搜索引擎使用案例
    jQuery 知识点积累
    Oracle 11g 卸载
    #region 自适应屏幕分辨率
    C#泛类型链表的实现
    C#可以获取Excel文件中Sheet的名字
    关于 List<T>
  • 原文地址:https://www.cnblogs.com/splendid/p/10329147.html
Copyright © 2011-2022 走看看