Saturday, 8 May 2021

Php: Add methods to the class definition

Functions defined inside a class are called methods. Methods are used to perform some action on instance/object properties.

 

Example

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

    function about_me(){
        echo "\nid : $this->id\n";
        echo "first_name : $this->first_name\n";
        echo "last_name : $this->last_name\n";
        echo "country : $this->country\n";
    }
}

 

Above snippet defines an Employee class and about_me function. As you observe the definition of about_me function, I am using $this(it is a special variable to access current instance properties inside the class) to access current object properties.

 

How to call the method using object?

Syntax

$object_name->method_name(arguments);

 

Example

$emp1 -> about_me();

 

Find the below working application.

 

instance_methods_demo.php

#!/usr/bin/php

<?php

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

        function about_me(){
            echo "id : $this->id\n";
            echo "first_name : $this->first_name\n";
            echo "last_name : $this->last_name\n";
            echo "country : $this->country\n";
        }
   }

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

Output

$./instance_methods_demo.php 

id : 1
first_name : Krishna
last_name : Gurram
country : India

 

 

 


 

 

 

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment