$this Keyword

The "$this" keyword is a significant component of PHP object-oriented programming (OOP). It allows you to reference the current object instance within a class. In this article, we will learn about $this keyword, how it works and how to use it effectively in your PHP projects with the help of examples.

 

About $this Keyword

Each object in PHP is an instance of a class, which functions as a blueprint for constructing objects. The $this keyword indicates that we are using the class's own methods and properties, and it allows us to access them within the scope of the class.

Using this keyword, we may access the class's properties and methods from within the class, as shown below:

<?php
$this->property;
$this->method();
?>

It indicates that we are using the class's own methods and properties, and it allows us to access resources that are only available within a class. It does not exist outside of the context of the class. When you use the $this keyword to access an object property, you only use the $ with the this keyword. You also don't utilize the $ symbol with the property name.

For example

<?php
class Student{
	
	public $name;
	private $age;
	
	public function getName()
	{
		
		return $this->name;
	}
	
	public function setAge($age){
		
		$this->age = $age;
	}
	
	public function getAge(){
		return $this->age;
	}
}

$obj1 = new Student();

$obj1->name = "Rohit Kumar";

echo "Your name is: ".$obj1->getName().'&lt;br/>';

$obj1->setAge(25);

echo "Your age is: ".$obj1->getAge();
?>

In above example, we are accessing the name & age property via the $this keyword inside the getName() and getAge() methods. Here, we assign any name to name variable by using

<?php
$obj1->name = "Rohit Kumar";
?>

and after that we are getting this name by using getName() method:

<?php
echo "Your name is: ".$obj1->getName().'<br/>';
?>

 

Also read about PHP OOPs Concept

Let's take one more example:

<?php

class Color{
	
	public $color;
	public $toyname;
	
	public function getColor()
	{
		return $this->color;
	}
	
	public function getToyName()
	{
		return $this->toyname;
	}
}

$obj2 = new Color();

$obj2->toyname = 'Teddy Bear';
$obj2->color = 'Yellow';

echo "My toy name is: ".$obj2->getToyName().'&lt;br/>';
echo "Color of my toy is: ".$obj2->getColor().'&lt;br/>';
?>

Here, we are using two property color & toy name & these two accessed by getColor() & getToyName() methods.

 

Conclusion

Working with objects in PHP requires the use of the "$this" keyword. It enables you to invoke methods, access properties, and use strong features like method chaining by allowing you to refer to the current object instance. Knowing how "$this" functions is essential to designing efficient object-oriented PHP code, and becoming proficient with it will improve your ability to create reliable and manageable apps.

Top