, , ,

What is $this keyword in PHP? Use cases of $this keyword

Posted by

Through this query, we will know about $this keyword in PHP and how can we use and apply it in PHP. So, first, we will define $this keyword. The $this keyword is an -> operator applied on the class and object and it only points to the current class object. you remove the $ sign in front of the property.

For ex:
$this ->color
class Fruit
{
public $color;
function showColor ($name)
{
$this ->color = $name;
echo “Color Name: $this ->color”;
}

$guava = new Fruit;
$guava ->showColor(‘green’);

I hope you will understand the concept behind the $this keyword and if you will run this below-mentioned code in your php program, it will definitely run and show an accurate result according to the below-provided code:

<?php
class Fruit{
  var $color1;   
  function showcolor(){
    echo $this->color;
  }
}
 
$guava = new Fruit;
$guava->color="Green";
$guava->showColor();
?>
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x