Open In App

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:

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
      // 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
    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/amp/


Article Tags :