In this tutorial, you will learn about PHP $this
keyword and how to use $this
inside a class.
In PHP,
$this
keyword references the current object of the classHere we can get a clear idea about $this keyword, Here the price of the car can access by the keyword $this
, can not access outside the class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | <?php class Car { var $price; var $color; /* Member functions */ function setPrice($car_price){ $this->price = car_price; } /* Member functions */ function getPrice(){ echo $this->price; } /* Member functions */ function setColor($car_color){ $this->color = car_color; } /* Member functions */ function getColor(){ echo $this->Color; } } $carObj = new Car(); $carObj->setPrice(500000); /* set the color of the car */ $carObj->setColor("red"); echo "The Car price: ".$carObj->getPrice(); /* get the color of the car */ echo "The Car color: ".$carObj->getColor(); ---------------------------- Output----------------------------------------- The Car price: 500000 The Car color: Red ?> |
Questions asked in the Interview on $this
- What is $this
Answer – $this is a keyword in PHP - How $this is used in Oops
Answer – This is used inside the class as a current object of the same class. By using $this we can access member functions and member variables inside the same class, outside access will show fatal error.