I try to call a member variable of a class from inside a method of the same class.
If I call it directly it doesn’t work, it requires to use the $this. Is there a reason for this? Can’t the class realize that the variable I am calling belongs to it?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The reason is more or less just because that’s how PHP works. It sounds like you are used to Java which automatically uses instance members in the current scope if there is not a local variable that overrides the member in the same scope. PHP does not grant you this liberty:
In Java, you would still have to use
this.yin the above example to printrbecause the class member name has been overridden locally. Just imagine that PHP’s members are always overridden in methods by void.