Saturday 15 May 2021

Php: Adding dynamic properties, overloading

If you set a value to an undefined property of object, Php internally defines the property and set the value.

 

Let’s see it with an example.

 

dynamic_properties_demo.php

#!/usr/bin/php

<?php

    class Employee{

    }

    $emp1 = new Employee();

    $emp1->id = 1;
    $emp1->first_name='Krishna';

    echo "id : $emp1->id\n";
    echo "first_name: $emp1->first_name";

?>

 

Output

$./dynamic_properties_demo.php 

id : 1
first_name: Krishna

 

As you see above example, I defined Employee class with no properties. But I defined properties id, first_name to the Employee object $emp1 dynamically.

 

Visibility vs dynamic properties

Due to the feature of dynamically adding properties to the object, you may feel that sometimes ‘private properties are visible in subclasses’, But that is not true. Let’s see this with an example.

 

dynamic_properties_demo_2.php

#!/usr/bin/php

<?php

    class Employee{
        private $org = 'ABC Corp';

        public function get_org(){
            return $this->org;
        }
    }

    class Manager extends Employee{

    }

    $emp1 = new Manager();

    $emp1->org = 'XYZ Corp';

    echo "\$$emp1->org : $emp1->org\n";
    echo "\$Actual organization: {$emp1->get_org()}";
?>

 

Output

$./dynamic_properties_demo_2.php 

$XYZ Corp : XYZ Corp
$Actual organization: ABC Corp

 

As you see Employee class, I defined a private property $org. Manager is a subclass of Employee class.

 

I created an instance of Manager class and defined a dynamic property org (which is same as parent class private property). This new dynamic property ‘org’ is nothing to do with the actual private property defined in parent class, you can confirm the same by calling get_org method of Employee class.

 

 

 

 

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment