why doesn't $this in PHP always refer to the current class?
I'm a Java developer who has turned to the dark side over the last couple of weeks as I've been trying to write some code in PHP for the first time ever.
Most stuff seems familiar, methods become functions, . becomes ->, variables have a $ in front and you never have any idea what 开发者_开发问答type they are, I get it, but I'm totally stumped by the $this keyword.
I expect $this to call a function in the current class as in java this.myCoolMethod(), but often as I poke through the open source project I'm going through, $this->myCoolMethod() calls a function in a totally different class!
What is happening here? What does '$this' actually mean?
Thank you for any help.
John
The reason it sometimes calls a method in a totally different class, is because that class probably extended another class with that method.
Here is a quick example:
class bla {
public function __construct() {}
public function whatwhat() {
echo "what....";
}
}
class lala extends bla {
public function __construct() {}
}
$lalaObj = new lala();
$lala->whatwhat();
As you can see, even though whatwhat() isn't in the class, it inherits it from the class it extends.
Hope that helps.
You should take a look at what Inheritance is.
$this
, within a method, refers to the object to which the method belongs. If an object belongs to a class that extends another class, then it may inherit methods from the parent class, which may be called using $this->method_name()
, just as with any other method.
$this actually refers to the current instance of the class.
$this->myCoolMethod() calls a function in a totally different class!
Can you provide an example of this? The only circumstance in which the myCoolMethod() might not be defined in the class itself is if it is defined in a parent or inherited class
$this
refers to whatever instance you're in. So if I extended Class_A
to become Class B
, and called methodName
within Class_B
, that would invoke Class_B::methodName
and not Class_A::methodName
.
I'm not sure how to explain clearer without knowing what context you're having difficulties, but try echoing __CLASS__
next to where you're using $this
to give you the current class's name you're in.
精彩评论