self:: Restriction instance analysis of PHP late static binding

  • 2021-11-13 00:56:40
  • OfStack

This article illustrates the self:: limitation of PHP late static binding. Share it for your reference, as follows:

Here I want to talk about post-static binding, and I want to talk about self:: And static Make a comparative explanation.

The official document defines it as follows:

"Late binding" means that static:: is no longer resolved to define the class in which the current method is located, but is evaluated at actual runtime. It can also be called "static binding" because it can be used for (but not limited to) static method calls.

Here I would like to use an example on the official document to illustrate self:: Limitation:

self:: Instance


class A{
  public static function who(){
   echo __CLASS__;
  }
  public static function test(){
   self::who();
  }
}
class B extends A{
  public static function who(){
   echo __class__;
  }
}
$B=new B();
$B->test();`

The output is:

A

static instance:


class A{
  public static function who(){
    echo __class__;
  }
  public static function test(){
    static::who();
  }
}
class B extends A{
  public static function who(){
    echo __class__;
  }
}
$B=new B();
$B->test();

The output is:

B

Attention, attention! Here we use: static:: I have rarely seen this writing in PHP before, have I? See static:: , can't help but think of: self:: parent::

Here I want to put self:: static:: parent:: Make a comparison:

self:: Usually pointing to the class itself, that is, self does not point to any instantiated object, while self is used to point to static variables in the class (not to non-static variables), but can access other static and non-static methods in the class. It is a pointer to the current class. parent:: Is a pointer to the parent class, so we use parent to call the constructor of the parent class. However, you can also access other methods of the parent class (you cannot access other static and non-static variables). static:: Usually used in late static binding.

For more readers interested in PHP related content, please check the topics on this site: "Introduction to php Object-Oriented Programming", "Encyclopedia of PHP Array (Array) Operation Skills", "Introduction to PHP Basic Grammar", "Summary of PHP Operation and Operator Usage", "Summary of php String (string) Usage", "Introduction to php+mysql Database Operation Skills" and "Summary of php Common Database Operation Skills"

I hope this article is helpful to everyone's PHP programming.


Related articles: