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则指向调用者的类。

  • 相关阅读:
    搜索1009
    搜索1004
    Java文件操作
    搜索1007
    连接查询
    SQL学习——数据类型
    SQL学习——基本语法
    <转载>GIS数据下载网站大全
    DOM查询练习
    day09【继承、super、this、抽象类】
  • 原文地址:https://www.cnblogs.com/flzs/p/15170101.html
Copyright © 2011-2022 走看看