Home  >  Article  >  Backend Development  >  Self in php represents the current class, so how to get the data of the access class?

Self in php represents the current class, so how to get the data of the access class?

autoload
autoloadOriginal
2021-03-12 15:03:251486browse

self is a static binding. In other words, when the class is compiled, self has been explicitly bound to the class name, so no matter how many inherit , regardless of whether subclass or parent class accesses it by itself, self represents the current class. If you want to selectively support visitors, you need to use static delayed binding.

Definition: static delayed binding, which is used inside the class The keyword part representing the class itself is not fixed when the class is compiled, but the class to which the visitor belongs is dynamically selected when the method is accessed. Static delayed binding is to use the static keyword instead of static bindingself. Static delayed binding requires the use of rewriting of static members.

1. Static delayed binding: Use the static keyword instead of self to class memberaccess

<?php
//父类
class People{
    public static $name = &#39;People&#39;;
    public static function showName(){
        //静态绑定
        echo self::$name,&#39;<br/>&#39;;//self
        //静态延迟绑定
        echo static::$name,&#39;<br/>&#39;;
    }
}
//子类
class Man extends People{
    //重写父类静态属性
    public static $name = &#39;Man&#39;;    //静态属性因为存储在类内部,因此不会覆盖
}

//子类访问

echo Man::$name."<br>";//Man
Man::showName();//输出People和Man
?>

2. Static delayed binding must be accessed through inherited subclasses to be effective

//接上述代码
People::showName();//输出People People

Recommended: php video tutorial

The above is the detailed content of Self in php represents the current class, so how to get the data of the access class?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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