Home>Article>Backend Development> The difference between new self() and new static() in PHP

The difference between new self() and new static() in PHP

coldplay.xixi
coldplay.xixi forward
2020-06-08 10:01:37 2534browse

The difference between new self() and new static() in PHP

The difference between new self() and new static() in PHP

new static() is in php5 .New features introduced in version 3

new static and new self() are both new objects

Look at the code directly

class Father { public function getNewFather() { return new self(); } public function getNewCaller() { return new static(); } } $f = new Father(); var_dump(get_class($f->getNewFather())); // Father var_dump(get_class($f->getNewCaller())); // Father

getNewFather and getNewCaller both return Father this Real column

It seems that there is no difference between new self() and new static() at this point

Then look at the following example

class Sun1 extends Father{ } $sun1 = new Sun1(); var_dump($sun1->getNewFather()); // object(Father)#4 (0) { } var_dump($sun1->getNewCaller()); // object(Sun1)#4 (0) { }

getNewFather returns the real column of Father ,

getNewCaller returns the caller’s actual column

Their difference can only be reflected in inheritance. If there is no inheritance, then there is no difference between the two

The actual column returned by new self() will not change. No matter who calls it, it will return an actual column of a class.

new static is determined by the caller.

Recommended tutorial: "PHP Video Tutorial"

The above is the detailed content of The difference between new self() and new static() in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:liqingbo.cn. If there is any infringement, please contact admin@php.cn delete