The difference between new self() and new static in PHP object-oriented

高洛峰
Release: 2016-11-16 11:13:26
Original
1202 people have browsed it

First clarify the conclusion. In PHP, self points to the class that defines the currently called method, and static points to the class that calls the current static method.

The following is an example to prove the above result

class A 
{
    public static $_a = 'Class A';
 
    public static function echoProperty()
    {
        echo self::$_a . PHP_EOL;
    }
}
 
class B extends A 
{
    public static $_a = 'Class B';
}
 
$obj = new B();
B::echoProperty();//输出 ‘Class A
Copy after login

The reason why this is the case is because using self:: or __CLASS__ to statically refer to the current class depends on the class in which the called method is defined. The above Class A The method echoProperty is modified to become:

class A 
{
    public static $_a = 'Class A';
 
    public static function echoProperty()
    {
        echo static::$_a . PHP_EOL;
    }
}
//再次调用B::echoProperty将输出   'CLASS B'
Copy after login

In order to avoid the subclass seen in the first example above overwriting the static properties of the parent class, using the inherited method to still access the static properties of the parent class, PHP5. 3 Added a new syntax: Late static binding, using the static keyword instead of the self keyword, so that static points to the same class returned by get_called_class(), that is, the class currently calling the static method. This key Words are also valid for access to static methods.

The following example better illustrates the difference between new self() and new static() (the latter uses PHP's late static binding to point to the current class of the calling method)

class A 
{
    public static function get_self() 
    {
        return new self();
    }
 
    public static function get_static() 
    {
        return new static();
    }
}
 
class B extends A {}
 
echo get_class(B::get_self());  // A
echo get_class(B::get_static()); // B
echo get_class(A::get_self()); // A
echo get_class(A::get_static()); // A
Copy after login


Related labels:
php
source:php.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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!