PHP Overloading

PHPServer Side ProgrammingProgramming

Introduction

Interpretation of overloading is different in PHP as compared to other object oriented languages such as C++ or Java wherein the term means ability to havea class with method of same name more than once but with different arguments and/or return type. In PHP on the other hand, the feature of dynamicaly creating properties and methods is known as overloading. PHP's magic methods (method names starting with double underscore) are used to set up dynamic properties and methods.

Following magic methods are used for overloading properties −

Syntax

public __set ( string $name , mixed $value ) : void
public __get ( string $name ) : mixed
public __isset ( string $name ) : bool
public __unset ( string $name ) : void

__set() is run for writing data to inaccessible properties that are protected or private or non-existing.

__get() reads data from inaccessible properties.

__isset() calls isset() or empty() on inaccessible properties.

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

In following code, a dynamic property named myprop is set, retrived and unset

Example

 Live Demo

<?php
class myclass{
   public function __set($name, $value){
      echo "setting $name property to $value \n";
      $this->$name = $value;
   }
   public function __get($name){
      echo "value of $name property is ";
      return $this->$name;
   }
   public function __isset($name){
      return isset($this->$name);
   }
   public function __unset($name){
      unset($this->$name);
   }
}
$obj = new myclass();
$obj->myprop="test";
echo $obj->myprop . "\n";
var_dump (isset($obj->myprop));
unset($obj->myprop);
var_dump (isset($obj->myprop));
?>

Output

The output is as below −

setting myprop property to test
test
bool(true)
bool(false)

Method overloading

Two magic methods used to set methods dynamically are __call() and __callStatic()

public __call ( string $name , array $arguments ) : mixed
public static __callStatic ( string $name , array $arguments ) : mixed

__call() is triggered when invoking inaccessible methods in an object context.

__callStatic() is triggered when invoking inaccessible methods in a static context.

Following exampe demonstrates method overloading in PHP

Example

 Live Demo

<?php
class myclass{
   public function __call($name, $args){
      // Note: value of $name is case sensitive.
      echo "Calling object method $name with " . implode(" ", $args). "\n";
   }
   public static function __callStatic($name, $args){
      echo "Calling static method $name with " . implode(" ", $args). "\n";
   }
}
$obj = new myclass();
$obj->mymethod("Hello World!");
myclass::mymethod("Hello World!");
?>

Output

Above code produces following result:

Calling object method mymethod with Hello World!
Calling static method mymethod with Hello World!
raja
Published on 18-Sep-2020 11:31:40
Advertisements