Saturday 8 May 2021

Php: Add properties to class definition

 

Every object in the world has some properties associated with it. For example, an employee has properties id, first_name, last_name etc.,

 

How to define a property?

Use var keyword followed by $variable_name inside class definition.

 

Can I set a default value to a property?

Yes, you can do.

 

Example

class Employee{

    var $id;

    var $first_name;

    var $last_name;

    var $country='India';

}

 

Above snippet defines an Employee with following properties.

a.   $id, $first_name and $last_name

b.   $country with default value as 'India'.

 

How to define values to instance properties?

Step 1: Define instance/object from a class.

$emp1 = new Employee;

  

Step 2: Use the syntax ‘$object_name -> property_name’ to set value to instance properties.

 

$emp1 -> id = 1;

$emp1 -> first_name = 'Krishna';

$emp1 -> last_name = 'Gurram';

 

Can I define multiple instances/object from same class definition?

Yes, you can do.

 

Find the below working application.

 

instance_properties_demo.php

#!/usr/bin/php

<?php

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

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

   $emp1 = new Employee;
   $emp1 -> id = 1;
   $emp1 -> first_name = 'Krishna';
   $emp1 -> last_name = 'Gurram';

   $emp2 = new Employee;
   $emp2 -> id = 2;
   $emp2 -> first_name = 'Gireesh';
   $emp2 -> last_name = 'Amara';
   $emp2 -> country = 'Australia';

   print_employee($emp1);
   print_employee($emp2);
?>

 

Output

$./instance_properties_demo.php 


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

id : 2
first_name : Gireesh
last_name : Amara
country : Australia

 

 

 

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment