PHP this Keyword is used to refer the current object. It is only available inside the method of the class. Basically, it refers to the object of the current method.
The general syntax for accessing class property and method.
$this -> propertyName;
$this -> methodName();
Note:Please keep in mind that, Only the $this
keyword starts with the $
. sign. Do not specify the $
sign before the property and method name.
Followings are the invalid syntax.
$this -> $propertyName;
$this -> $methodName();
Source Code
<?php
class Car {
// The properties
public $color = 'white';
public $carModel = "XYZ102";
// The method can now approach the class properties
// with the $this keyword
public function carBasicInfo()
{
return "The available car model is ".$this->carModel." and having color".$this->carModel;
}
}
$carObj = new Car();
$carObj->carBasicInfo();
?>