Home  >  Article  >  Backend Development  >  PHP’s new static and new self

PHP’s new static and new self

藏色散人
藏色散人forward
2019-09-26 09:18:122402browse

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

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 这里
}

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!

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