How will you access the reference to same object within the object in PHP ?

In this article, we will see how we can access the reference to the same object within that object in PHP.
To do that we have to use the “$this” keyword provided by PHP.
PHP $this Keyword:
- It is used to refer to the current object
- It can only be used inside the internal methods of the class.
- $this keyword can refer to another object only if it is inside a static method and it is called from the context of a secondary object.
- It is generally used in constructors to store the value inside the object’s variables.
Example 1: Let’s see a simple example of using $this in PHP. We have a class GFG that is having a “$value” variable and a “show()” function to return the value.
PHP
<?php // this keyword example class GFG { public $value = 10; public function show() { // referencing current object // within the object return $this -> value; } } $obj = new GFG(); echo $obj -> show(); ?> |
Output:
10
Example 2: We have created a Class “Vegetable” having $name and $color properties and we are using $this keyword to access the methods.
PHP
<?php class Vegetable { public $name; public $color; function set_name($name) { $this->name = $name; } function get_name() { return $this->name; } } $carrot = new Vegetable (); $ladyfinger = new Vegetable (); $carrot->set_name('Carrot'); $ladyfinger->set_name('Ladyfinger'); echo $carrot->get_name(); echo "<br>"; echo $ladyfinger->get_name(); ?> |
Output:
Carrot Ladyfinger
Reference: https://www.zambiatek.com/this-keyword-in-php/
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, zambiatek Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!



