Is this $this needed since we know the code is contained within the function [closed]

StackOverflow https://stackoverflow.com/questions/22661172

  •  21-06-2023
  •  | 
  •  

Question

If $this references its own instance of a class. Would it make a difference if it were omitted since we know what '$this' is references as its always within the instance created.

E.g.

Class examp {

Public Function getName($name) {

$this->$name=name; 

}

E.g. 2 with $this omitted

Class examp {

Public Function getName($name) {

$name=name;

}
Was it helpful?

Solution

In the first example $this->name will never point to the parameter, as you're explicitly referencing the property name of the current object $this.

As for the second example you're simply referencing the parameter, and this difference is one of the reasons $this is used/omitted.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top