Home > Backend Development > PHP Tutorial > The difference between new self() and new static() in PHP object-oriented

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

藏色散人
Release: 2023-04-07 17:42:01
forward
2822 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.

Next, use 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 self:: or __CLASS__ is used to statically refer to the current class, depending on the definition of the called method. In the class where it is located, modify the method echoProperty of Class A above 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 from overwriting the static properties of the parent class, use the inherited The method still accesses the static properties of the parent class. PHP5.3 adds a new syntax: Late static binding. Use the static keyword instead of the self keyword to make static point to the same class returned by get_called_class(). , that is, the class currently calling the static method, this keyword is also valid for accessing the static method.

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

For more PHP related knowledge, please visit PHP Chinese website!

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

Related labels:
php
source:segmentfault.com
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