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

  • 相关阅读:
    php wamp 配置虚拟主机
    php xml 操作。
    第一个输入框中 输入 test,第二个输入框中自动出现 test.baibu.com
    正则表达式 手机号码的验证
    JQery 设置 退格键 不可用 jQery 中的keydown 事件
    YII 片段缓存如何实现。
    php set_time_limit() 函数
    VLAN
    进程
    802.11无线网络权威指南
  • 原文地址:https://www.cnblogs.com/splendid/p/10329147.html
Copyright © 2011-2022 走看看