Home > Backend Development > PHP Tutorial > PHP Static delayed static binding usage analysis

PHP Static delayed static binding usage analysis

高洛峰
Release: 2023-03-04 10:52:01
Original
1177 people have browsed it

The example in this article describes the usage of PHP Static delayed static binding. Share it with everyone for your reference, the details are as follows:

After PHP5.3, delayed static binding static was introduced. What problem is it intended to solve? A long-standing problem in PHP's inheritance model is that it is difficult to reference the final state of an extended class in the parent class. Let’s look at an example.

class A 
{ 
  public static function echoClass(){ 
    echo __CLASS__; 
  }
  public static function test(){ 
    self::echoClass();    
  }
}
class B extends A 
{    
  public static function echoClass() 
  { 
     echo __CLASS__; 
  } 
} 
B::test(); //输出A
Copy after login

A new feature has been added to PHP5.3: delayed static binding, which means that expressions or variables that were originally fixed in the definition phase are changed to be determined in the execution phase, such as when a subclass inherits When a static expression of the parent class is added, its value cannot be changed. Sometimes you do not want to see this situation.

The following example solves the problem raised above:

class A 
{ 
  public static function echoClass(){ 
    echo __CLASS__; 
  } 
  public static function test() 
  { 
    static::echoClass();    
  } 
} 
class B extends A 
{    
  public static function echoClass(){ 
     echo __CLASS__; 
  } 
} 
B::test(); //输出B
Copy after login

static::echoClass(); on line 8 defines a static delayed binding method until B calls test Execute the method that is executed when originally defined.

Hope this article will be helpful to everyone in PHP programming.

For more articles related to PHP Static delayed static binding usage analysis, please pay attention to 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