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

coldplay.xixi
Release: 2023-04-08 19:02:01
forward
2649 people have browsed it

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
Copy after login

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) { }
Copy after login

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!

Related labels:
source:liqingbo.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template