Overloading in PHP


Overloading:


Overloading in PHP provides means to dynamically "create" properties and methods. These dynamic entities are processed via magic methods one can establish in a class for various action types. ... All overloading methods must be defined as public.

According to Object Oriented Programming (OOP) concept if a class has methods of the same name but different parameters then we say that we are overloading that method. Also if we were to create a method in the child class having the same name, same number of parameters and the same access specifier as in its parent then we can say that we are doing method overriding.


PHP’s Overloading Types

Overloading in PHP can be classified as,

1.Property Overloading

2.Method Overloading


Property Overloading:

PHP property overloading enables us to make dynamic properties in the object setting. For making those properties no different line of code is required. A property related with the class instance, and it isn’t declared inside the extent of the class, is considered as overloaded property.

In below we will learn about some uses of overloaded properties in PHP.

Setting and getting overloaded properties.

Evaluating overloaded properties setting.

Undo such properties setting.

PHP property overloading use some magic methods. Which are described below.

__set() is run when writing data to inaccessible properties.

__get() is utilized for reading data from inaccessible properties.

__isset() is triggered by calling isset() or empty() on inaccessible properties.

__unset() is invoked when unset() is used on inaccessible properties.

Program:

<?php class PropertyOverload

{

   /**  Location for overloaded data.  */

   private $data = array();

   public function __set($name, $value)

   {

       $this->data[$name] = $value;

   }

public function __get($name)

   {

   return $this->data[$name];

   }

   public function __isset($name)

   {

       return isset($this->data[$name]);

   }

   public function __unset($name)

   {

       unset($this->data[$name]);

   }

}

$obj = new PropertyOverload;

$obj->name = "567-Ashtokumar yadav";

echo $obj->name; // 567-Ashtokumar yadav

?>

Output:

567-Ashtokumar yadav


In the above example PHP program, the dynamic property is created. While initializing this dynamic property, __set() is invoked with name and value pair to be initialized as the name and value of class property array element $data.

Added to that, isset() and unset() with overloaded property will trigger __isset() and __unset() magic methods.

Custom Search

%d bloggers like this: