Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialprabhu lingam
6,955 Pointsthis keyword
i am not able to understand this keyword . Can anyone please explain about it in detail
2 Answers
Christian Andersson
8,712 PointsThis is a keyword that you'll see alot of in, not just php, but nearly all object-oriented programming languages.
The this
-keyword is basically a reference to the current object. Here is an example:
Class Car
{
public $manufacturer; //this is a variable of the Car-class and will store the manufacturer-name for a Car-object.
public $model; //this is also a variable of the Car-class and will store the model-name for a Car-object.
function __construct( $manufacturer, $model ) {
$this->manufacturer = $manufacturer;
$this->model = $model;
}
};
$car1 = new Car('Volvo', 'XC90');
echo $car1->manufacturer;
echo $car1->model;
$car2 = new Car('Ferrari', 'F50');
echo $car2->manufacturer;
echo $car2->model;
So in the above code you have a class that has 2 attributes: $manufacturer
and $model
. When you create a new Car-object, these 2 properties are given to the object. So you can read $this
as "The current object".
So where it says $this->model = $model;
you can read as "The current objects model is = the variable $model".
You can then grab these properties by referencing the object (here $car1 or $car2) and then its' property-name.
From php.net manual:
The pseudo-variable $this is available when a method is called from within an object context. $this is a reference to the calling object (usually the object to which the method belongs, but possibly another object, if the method is called statically from the context of a secondary object).
http://www.php.net/manual/en/language.oop5.basic.php
Hope this helps
Shafeeq Ahmed
6,058 Pointsthis key word represent the current instance. $this->property means property of the object you replace $this keyword.