Open In App

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

Last Updated : 14 Dec, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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.geeksforgeeks.org/this-keyword-in-php/



Like Article
Suggest improvement
Share your thoughts in the comments