silverglade Posted June 14, 2011 Share Posted June 14, 2011 Hi, I do not know why we have to use the $this statement to refer to a variable within the same class. Take this code for example. class Car { var $gas = 0; function addGas($amount) { $this->gas = $this->gas + $amount; echo "$amount gallons added to gas tank"; } } why do we need "$this"? why cant we just write "$gas+= $amount;". Any help greatly appreciated. thanks. Link to comment https://forums.phpfreaks.com/topic/239379-question-about-the-use-of-the-this-statement/ Share on other sites More sharing options...
jcbones Posted June 14, 2011 Share Posted June 14, 2011 function scope. You could use $gas in the function, but it would only be a variable of the function. $this refers to the object, so, when you refer to an object variable, you must use $this. Link to comment https://forums.phpfreaks.com/topic/239379-question-about-the-use-of-the-this-statement/#findComment-1229802 Share on other sites More sharing options...
silverglade Posted June 14, 2011 Author Share Posted June 14, 2011 Great answer jcbones. Thanks very much. I understood that answer completely. Thank you. :) Link to comment https://forums.phpfreaks.com/topic/239379-question-about-the-use-of-the-this-statement/#findComment-1229803 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.