Home > Backend Development > PHP Tutorial > PHP's new static and new self

PHP's new static and new self

藏色散人
Release: 2023-04-07 13:10:02
forward
2575 people have browsed it

Let’s give a chestnut below:

class Father {
    public static function getSelf() {
        return new self();
    }
    public static function getStatic() {
        return new static();
    }
}
class Son extends Father {}
echo get_class(Son::getSelf()); // Father
echo get_class(Son::getStatic()); // Son
echo get_class(Father::getSelf()); // Father
echo get_class(Father::getStatic()); // Father
Copy after login

new self

Note here that this line get_class(Son::getStatic()); returns Son. class, can be summarized as follows:

self returns the class in which the keyword new in new self is located, such as the example here:

public static function getSelf() {
    return new self(); // new 关键字在 Father 这里
}
Copy after login

always returns Father.

new static

static Based on the above, it is a little smarter: static will return the class that executes new static(), such as Son executing get_class(Son: :getStatic()) returns Son, Father. Executing get_class(Father::getStatic()) returns Father

. In the absence of inheritance, it can be considered that new self and new static return the same result.

The above is the detailed content of PHP's new static and new self. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
source:dmzfa
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