Sunday 9 May 2021

Php: $this: refer to current instance properties

When you are inside a class definition, you should use the special variable $this, to refer current instance properties or methods.

 

Example

$this->first_name;

$this->print_full_name();

 

Find the below working application.

 

this_variable_demo.php

#!/usr/bin/php

<?php

   class Employee{
        var $id;
        var $first_name;
        var $last_name;
        var $country='India';

        function print_full_name(){
            $full_name = $this->first_name . ',' .$this->last_name;
            echo "full_name: $full_name";
        }
        function about_me(){
            echo "id : $this->id\n";
            $this->print_full_name();
            echo "\ncountry : $this->country\n";
        }
   }

   $emp1 = new Employee;
   $emp1 -> id = 1;
   $emp1 -> first_name = 'Krishna';
   $emp1 -> last_name = 'Gurram';
   
   $emp1 -> about_me();
?>

 

Output

$./this_variable_demo.php 

id : 1
full_name: Krishna,Gurram
country : India

 

 

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment