Home > Backend Development > PHP Problem > 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
Release: 2023-03-08 12:40:02
Original
1978 people have browsed it

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
?>
Copy after login

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
?>
Copy after login

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!

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