PHP this Keyword

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.

How To Access Class Property & 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();
?>
        
Try it now

Web Tutorials

PHP this Keyword
Html Tutorial HTML
Javascript Tutorial JAVASCRIPT
Css Tutorial CSS
Bootstrap 5 Tutorial BOOTSTRAP 5
Bootstrap 4 Tutorial BOOTSTRAP 4