, , ,

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

Posted by

Upgrade & Secure Your Future with DevOps, SRE, DevSecOps, MLOps!

We spend hours scrolling social media and waste money on things we forget, but won’t spend 30 minutes a day earning certifications that can change our lives.
Master in DevOps, SRE, DevSecOps & MLOps by DevOps School!

Learn from Guru Rajesh Kumar and double your salary in just one year.


Get Started Now!

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