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

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

藏色散人
藏色散人forward
2019-10-23 13:47:032718browse

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

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'

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

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!

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