Home > Article > Backend Development > Explanation of the differences between this, self and parent in php
illustrate:
The this pointer is used in statements ① and ②, so who does this point to at that time?
In fact, this determines who it points to when instantiating it. For example, when the object is instantiated for the first time (statement ③), then this is pointing to the $obj1 object. Then when executing the print of statement ②, print( $this-> Let’s look at the usage of self. Self points to the class itself, that is, self does not point to any instantiated object. Generally, self is used to point to static variables in the class. If you use a static member in a class (usually using the keyword static), you must use self to call it. Note that using self to call static variables must use :: (field operator symbol), see example.
Note: Statement ① and Statement ②. A static variable $firstCount is defined in statement ①, then self is used to call this value in statement ②. At this time, the static variable $frestCount defined by the class itself is called. Static variables have nothing to do with the instances of the following objects. They are only related to the class. If you call the class itself, you cannot use this to reference it, because self points to the class itself and has nothing to do with any object instance. Then, the this used earlier calls the instantiated object $obj. Finally, we will explain the usage of parent. Parent is a pointer to the parent class. Generally, parent is used to call the constructor of the parent class. Example:
which also contains the usage of this. Details: Member properties are all public (public properties and methods, accessible to code inside and outside the class), especially those of the parent class. This is for inherited classes to access through this. The key point is statement ①: parent::__construct( "heiyeluren" ). At this time, parent is used to call the constructor of the parent class to initialize the parent class. In this way, the objects of the inherited class are assigned the name PBPHome. We can test it by instantiating another object $personObject1. After printing, the name is still PBPHome. Summary: this is a pointer to an object instance, which is determined when instantiated; self is a reference to the class itself, generally used to point to static variables in the class; parent is a reference to the parent class. Generally, parent is used to call the constructor of the parent class. With the above introduction combining theory and examples, have you already had a deep understanding of these three keywords: this, self, and parent? Programmer's Home, I wish you all the best in your studies and progress. |