+ 1
Hi, can anyone tell me a better decribe from "this"
this
4 Answers
+ 3
this is used to access current object of a class and all oop language term shows nearly same behavior. It is not depend upon language java, c++, PHP and other oop language show same oop characteristics behavior.
+ 1
i wanted this in java and not in php but thank you
+ 1
The 'this' keyword refers to the current instance/object your code runs inside (in non-static context).
Non-static methods can access the instance they are called upon like:
class X {
String NotStatic() {
X instace = this;
return instance.toString();
}
}
While the 'this' keyword cannot be used in static methods, because there is no instance the method is called on.
In the example above instance.toString() is the same as calling simply toString() - just to show some code - but it can be needed when - for example - you want to pass the current object as parameter:
void addToList(List<Object> list) {
list.add(this);
}
Also, by using it variable shadowing can be avoided, like in case of costructors:
class Foo {
int x;
public Foo(int x) {
//x = x; <-- /nothing/ happens
this.x = x; //writes into local x
}
}
0
in PHP this points to the object where you in.
for example there is a class car with a method drive and a property speed and you want to echo the speed on the drive method your function could look like this:
public function drive{
echo "speed:".$this->speed;
}
i hope this helps someway ^^