Home > Backend Development > PHP Tutorial > Detailed explanation of PHP delayed static binding static

Detailed explanation of PHP delayed static binding static

小云云
Release: 2023-03-22 10:02:01
Original
1319 people have browsed it

In the old version of PHP, return new self() is used to return an instance of this class; but this method has a big drawback, that is, self refers to the parsing context rather than the calling context. This article mainly shares with you the detailed explanation of PHP delayed static binding static. I hope it can help you.

abstract class father { 

    public static function create() { 

        return new self(); 

    } 
} 
class son1 extends father { 
} 
son1::create();
Copy after login

That is to say, the subclass calling the create() method in the above code actually returns an instance of the parent class, because self points to the place where it is defined rather than the place where it is called, and father If the class is an abstract class, this code will report a fatal error. <br/>

Delayed static binding was introduced after PHP5.3, using the static keyword. <br/>

abstract class father { 

    public static function create() { 

        return new static(); 

    } 
} 
class son1 extends father { 
} 
son1::create();
Copy after login

Change self to static and it will execute normally, because static points to the called class rather than the defined class.

We can also use static as the identifier of a static method, even when called from a non-static context. I’ll write about this later.

Related recommendations:

php implements late static binding

php late static binding example detailed explanation

What is php delayed static binding? Detailed explanation of delayed static binding example code

The above is the detailed content of Detailed explanation of PHP delayed static binding static. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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