My question is about the design purpose of $this
. Why use $this
within a class to call a member function, isn't the class aware of its own functions, and aren't the functions aware of each other therein?
It's like a sister calling her brother - Hey, my brother Mark, the son of Mary who is also my mother, come over here;
Did I make myself clear? I couldn't find a similar question, and I don't think it's a duplicate.
Okay, let's say if you wouldn't have to use $this
:
<?php
function x(){echo "nope";}
class A {
function x(){echo "x";}
function y(){x();}
}
$o = new A;
$o->y();
?>
So this would call now the function x()
in the class A. Means output is x
, but if you now don't want to call the function x()
from the class, but the other one, how do you want to say that? telekinesis?
How would you be able to call functions which aren't in the class, but have the same name as a class method? Do you want so that you can't use any functions from outside of the class definition?
So that's why you "say"($this
) that you now call a method from the class!