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

  • 相关阅读:
    [LeetCode] 617. Merge Two Binary Trees
    [LeetCode] 738. Monotone Increasing Digits
    289. Game of Life
    305. Number of Islands II
    288. Unique Word Abbreviation
    271. Encode and Decode Strings
    393. UTF-8 Validation
    317. Shortest Distance from All Buildings
    286. Walls and Gates
    296. Best Meeting Point
  • 原文地址:https://www.cnblogs.com/splendid/p/10329147.html
Copyright © 2011-2022 走看看