Home  >  Article  >  Backend Development  >  Does self represent the current class or the access class in inheritance?

Does self represent the current class or the access class in inheritance?

autoload
autoloadOriginal
2021-03-04 10:18:021915browse

selfThe keyword is used to replace the class inside the class, replacing the class itself where the current method is located. With the implementation of inheritance, if sub When class accesses parent class method , does self replace the current class or the accessing class?

<?php
   class Fu{
       public static $type="Fu";
       public static function getType(){
           echo self::$type." self<br>";
           
       }
   }

   class Zi extends Fu{
    public static $type="Zi";
    
   }
   Fu::gettype();//Fu self
   Zi::gettype();//Fu self
?>

As shown in the above example, self represents the current class, that is, the parent class in which it is located, not the inherited subclass.

If you dynamically select the class to which the visitor belongs when the method is accessed, you need to use the static key instead of self to access class members.

<?php
   class Fu{
       public static $type="Fu";
       public static function getType(){
           echo self::$type." self<br>";//类的静态绑定
           echo static::$type." static<br>";//类的静态延迟绑定
       }
   }

   class Zi extends Fu{
    public static $type="Zi";
    
   }

   Fu::gettype();//Fu self Fu self
   Zi::gettype();//Fu self Zi static
?>

Recommended: php tutorial,php video tutorial

The above is the detailed content of Does self represent the current class or the access class in inheritance?. 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