Comparison between new static () and new self () in PHP, staticself
Today in coding, I found new static (). Do I think the instantiation should be new self? After querying, you can see the differences between the two:
1) when sub-classes are integrated, the performance of the two is different.
2) php 5.2 and earlier versions do not support the new static () syntax.
The specific explanation is as follows: self-is the class in the code snippet. Static-PHP 5.3 only adds the current class, which is a bit like $ this. It is extracted from the heap memory and accessed by the class currently instantiated, static indicates the class. Let's take a look at the foreign professional explanation: self refers to the same class whose method the new operation takes place in. static in PHP 5.3's late static bindings refers to whatever class in the hierarchy which you call the method on. in the following example, B inherits both methods from. self is bound to A because it's defined in A's implementation of the first method, whereas static is bound to the called class (also see get_called_class ()).
Code:
1 class Person { 2 public static function get_self() { 3 return new self(); 4 } 5 6 public static function get_static() { 7 return new static(); 8 } 9 }10 11 class WangBaoqiang extends Person{}12 13 echo get_class(WangBaoqiang::get_self()); // Person14 echo get_class(WangBaoqiang::get_static()); // WangBaoqiang15 echo get_class(Person::get_static()); // Person
However, if you want the subclass to use get_class, the returned value is also the name of the current subclass ('wangbaoqiang '). How can this problem be solved.
<?phpclass Person { public function create1() { $class = get_class($this); return new $class(); } public function create2() { return new static(); }} class WangBaoqiang extends Person { } $wangBaoQiang = new WangBaoqiang();var_dump(get_class($wangBaoQiang->create1()), get_class($wangBaoQiang->create2())); /*The result string(1) "WangBaoqiang"string(1) "WangBaoqiang"*/
Thank you for your criticism.