Late static binding after PHP OOP

*文
Release: 2023-03-18 15:40:02
Original
1380 people have browsed it

This article mainly introduces the post-static binding function of PHP object-oriented. This article will introduce the late static binding function of PHP, which is mainly used to solve the problem of referencing statically called classes in the inheritance scope. I hope to be helpful.

This article will introduce the PHP late static binding function, It is mainly used to solve the problem of referencing statically called classes in the inheritance scope.

First look at the following example:

class Person
{
 
    public static function status()
    {
        self::getStatus();
    }
 
    protected static function getStatus()
    {
        echo "Person is alive";
    }
 
}
 
class Deceased extends Person
{
 
    protected static function getStatus()
    {
        echo "Person is deceased";
    }
 
}
 
Deceased::status(); //Person is alive
Copy after login

Obviously, the result is not what we expected. This is because self:: depends on the class in which it is defined, not the running class. In order to solve this problem, you may override the status() method in the inherited class. A better solution is that PHP 5.3 added the function of late static binding.

class Person
{
 
    public static function status()
    {
        static::getStatus();
    }
 
    protected static function getStatus()
    {
        echo "Person is alive";
    }
 
}
 
class Deceased extends Person
{
 
    protected static function getStatus()
    {
        echo "Person is deceased";
    }
 
}
 
Deceased::status(); //Person is deceased
Copy after login

It can be seen that static:: no longer points to the current class. In fact, it is calculated at runtime, forcing all properties of the final class to be obtained.

Therefore, it is recommended that you do not use self:: in the future and use static::

Related recommendations:

php object-oriented transaction script mode

PHP object-oriented final class and final method

PHP Object-Oriented Detailed Explanation_PHP Tutorial

The above is the detailed content of Late static binding after PHP OOP. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!