As we know before, the attributes and methods of accessing object members outside the object are completed by referencing the object. In an object, the member method accesses other member attributes or member methods in its own object, and uses a special object reference $ this-value to access the object where the member belongs, $ this reference represents the object and can only be used in the object's member methods. Let's take a look at the example below. What is $ this doing? As we know before, the attributes and methods of accessing object members outside the object are completed by referencing the object. In the object, the member method accesses other member attributes or member methods of the object, and must be accessed in the form of a special object reference "$ this-> value, $ this indicates the object to which the member belongs and can only be used in the member method of the object.
Let's take a look at the example below. What is $ this doing?
Name. "said,". "His side". $ this-> run (). "One Side". $ this-> eat ("apple ")."
";} Public function eat ($ name) {return" eat ". $ name;} public function run () {return "Walking" ;}}$ Person1 = new Person (); $ Person2 = new Person (); $ Person1-> name = "Zhang San"; $ Person2-> name = "Li Si"; $ Person1-> say (); $ Person2-> say ();?>
The above program running result:
Michael said he was walking and eating apple
Li said that he eats apple while walking
Let's take a look at what $ this has done in the above Code:
1. Access members of an object, such as $ this-> name
2. Other methods for accessing objects, such as the $ this-> run () and $ this-> eat ("apple") Methods outside of the say () method.
It is worth noting that local variables and member attributes can have the same name, but their scopes and access methods are different. For example, $ name in the eat () method is equivalent to a local variable, the function scope is limited to the eat method, while the $ name in the member attribute declaration of Person is equivalent to a global variable, which can be accessed in the form of $ this-> name in other methods.