Skip to main content

Polymorphism in php with example

What is polymorphism in php?

Polymorphism in PHP is a concept by which we can perform a single action in different ways. Polymorphism is derived in two from Greek word “poly” and “morphism”.

"Poly" means many and "morphism" means (forms) property which help us to assign more than one property.

# Types of polymorphism :

There are two types of Polymorphism:

  • Overriding(Run-time polymorphism).

  • Overloading(Compile-time polymorphism).

1.) Method Overriding : Method overriding is one of the ways in which Php supports Runtime Polymorphism. If same functions defined in parents and child class with same signature know as function overriding.

  • It is also known as dynamic binding or late binding.

Let’t see an example of Function overriding :

  ➤ Example : function overriding;

  1. <?php

  2. class ParentClass {

  3. public function myMessage(){

  4.   echo "Parent-Class method called";

  5. }

  6. }

  7. class ChildClass extends ParentClass{

  8. public function myMessage(){

  9.   echo "Child-Class method called";

  10. }

  11. }

  12. $obj = new ChildClass(); // Creating object for ChildClass

  13. $obj -> myMessage(); // Method callng

  14. ?>

Output :
  • Child-Class method called

2.) Overloading : If a class has multiple functions having same name but different in parameters, It is known as function overloading.

  • It contains the same function name and that function preforms different tasks according to the number of arguments.

  • It is also known as static or early binding.

Note : Like other OOP programming languages function overloading, PHP can not be done by native approach.

In PHP function overloading is done with the help of magic function __call() and this function takes parameter( name and arguments).

Let's see, by the simple example :

  ➤ Example : overloading;

<?php
  class Overloading{
    function sum($a, $b){
      echo $a+$b;
    }
    function sum($a, $b, $c){
      echo $a+$b+$b; 
    }
  }
  $obj = new Overloading(); // Creating object
  $obj -> sum(10, 20); 
  $obj -> sum(11, 22, 33); 
?>
Output :
  • Fatal error: Cannot redeclare PropertyOverload::sum() in Overloading.php on line 6


Important "Property" and "Rules" of overloading in PHP:

  • overloading methods must be defined as public

  • After creating the object for a class, we can access a set of entities that are methods or properties not defined within the scope of the class.

  • Such entities are said to be overloaded properties or methods, and the process is called as overloading.

  • For working with these overloaded properties or methods, PHP magic methods are used.

  • Most of the magic methods will be triggered in object context except __callStatic() method which is used in a static context.

There are two types of overloading in PHP:

  • Property overriding.

  • Method overloading.

2.1 ) Property Overriding : PHP property overloading is used to create dynamic properties in the object context.

  • A property associated with a class instance, and if it is not declared within the scope of the class, it is considered as overloaded property..

Note : For creating these properties no separate line of code is needed.

There are following operations performed with overloaded properties in PHP:
  1. Setting and getting overloaded properties.

  2. Evaluating overloaded properties setting.

  3. Undo such properties setting.

  4. Before performing the operations, we should define appropriate magic methods. which are,

    • __set() - __set() method is run when writing data to inaccessible (private or protected) or non-existing properties.

    • __get() - __get() methog is utilized for reading data from inaccessible (private or protected) or non-existing properties.

    • __isset() - __isset() magic method is invoked when we check overloaded properties with isset() function

    • __unset() - Similarly, this function will be invoked on using PHP unset() for overloaded properties.

Let's try, to create simple example :

  ➤ Example : property overriding;

  1. <?php

  2. class PropertyOverloading {

  3. // Location of overloading data

  4. private $data = array();

  5.  

  6. // Overloading not used on declared properties.

  7. public $declared = 1;

  8.  

  9. // Overloading only used on when accessed outside the class.

  10. private $hidden = 2;

  11.  

  12. // Function definition

  13. public function __set($name, $value){

  14.   echo "Setting '$name' to '$value'\n";

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

  16. }

  17. // Function definition

  18. public function __get($name){

  19.   echo "Getting '$name': ";

  20. if(array_key_exists($name, $this->data)){

  21.   return $this->data[$name];

  22. }

  23.   $trace = debug_backtrace();

  24.   return null;

  25. }

  26. // Function definition

  27. public function __isset($name){

  28.   echo "Is '$name' set? \n";

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

  30. }

  31. // Definition of __unset function

  32. public function __unset($name){

  33.   echo "Unsetting '$name'\n";

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

  35. }

  36. // getHidden functinon definition

  37. public function getHidden(){

  38.   return $this->hidden;

  39. }

  40. }

  41.  

  42. $obj = new PropertyOverloading(); // Create an object

  43.  

  44. // Set value 1 to the object variable

  45. $obj->a = 1;

  46. echo $obj->a . "\n";

  47.  

  48. // Use isset function to check

  49. var_dump(isset($obj->a)); // 'a' is set or not

  50.  

  51. unset($obj->a); // Unset 'a'

  52.  

  53. var_dump(isset($obj->a));

  54.  

  55. echo $obj->declared . "\n\n";

  56.  

  57. echo "Private property are visible inside the class";

  58. echo $obj->getHidden() . "\n\n";

  59.  

  60. echo "Private property are not visible outside of class\n";

  61. echo $obj->hidden . "\n";

  62. ?>

Output :
  • Setting 'a' to '1'

  • Getting 'a: 1

  • Is 'a' set?

  • bool(true)

  • Unsetting 'a'

  • Is 'a' set?

  • bool(false)

  • 1

  •  

  • Private property are visible inside the class 2

  •  

  • Private property are not visible outside of class

  • Getting 'hidden:

2.2 ) Method Overloading : It is a type of overloading for creating dynamic methods that are not declared within the class scope. PHP method overloading also triggers magic-methods dedicated to the appropriate purpose, Unlike property overloading.

PHP method overloading allows function call on both static and object context, The related magic functions are following,

  • __call() - It is triggered when invoking inaccessible methods in the object context.

  • __callStatic() - It is triggered when invoking inaccessible methods in static context.

Note : value of $name in '__call' and '__callStatic' is case sensitive.

Let's try, to create simple example :

  ➤ Example : method overriding;

  1. <?php

  2. class MethodOverloading {

  3. public function __call($name, $arguments){

  4.   echo "Calling object method '$name'"

  5.    . implode(', ', $arguments) . "\n";

  6. }

  7. public static function __callStatic($name, $arguments){

  8.   echo "Calling static method '$name'"

  9.    . implode(', ', $arguments) . "\n";

  10. }

  11. }

  12. $obj = new MethodOverloading(); // Create an object

  13. $obj -> runTest('in object context');

  14. MethodOverloading::runTest('in static context');

  15. ?>

Output :
  • Calling object method 'runTest' in object context

  • Calling static method 'runTest' in static context

Comments

Popular Posts

How to remove the date and .html from every blogger post url

#Remove date and .html from blogger post url A Common search term which every blogger search is How to Remove Date From Blogger Post URL or how do I remove date from blogger permalink? Follow the steps below and then date and .html will be removed from the URL of your blogger post. Step 1 : Login to your Blogger blog and select Theme / Template. Step 2 : Click on Edit HTML and paste the below code just above the </head> tag let's see code :   ➤ Code : mycode.js; Copy code <script type='text/javascript' > //<![CDATA[ // BloggerJS v0.3.1 var urlTotal,nextPageToken,postsDatePrefix=!1,accessOnly=!1,useApiV3=!1,apiKey="",blogId="",postsOrPages=["pages","posts"],jsonIndex=1,secondRequest=!0,feedPriority=0,amp="&"[0];function urlVal(){var e=window.location.pathname,t=e.length;return...

Django static files not working when debug false || debug true

# Django static and media files not working when debug is false In this article you will learn how to fix problem of not loading static files and media in Django even the DEBUG is FALSE. This is the easiest and safest solution. # Problem: Django static and media files not working when debug is false  ➤ Code: settings.py DEBUG = False #True ALLOWED_HOSTS = [ '*' ] #Host name # Problem Fix: Let's see, How you can fix the problem of Django static and media files not working when DEBUB = False : 1.)First way: devserver in insecure mode If you still need to server static locally ( e.g. for testing without debug ) you can run devserver in insecure mode: python manage.py runserver --insecure --insecure: it means you can run serve...

How to remove ? m=1 or ?m=0 from blogger post URL

# Remove m=1 From URL of Blogger post A Common search term that every blogger search is How to ?m=1 or ?m=0 from blogger Post URL. We all know that "simplicity is beauty" and you want to clean permalink. So, in this article, I will guide you on how to remove ?m=1 from the blogger URL, and make a simple professional URL. Follow the few steps below and removed ?m=1 from the URL of your blogger post. Step 1 : First, you login into your blogger's dashboard and then select your blog. Step 2 : Click on the Theme option. Step 3 : Click on the customise Step 4 : Click on Edit HTML option. Step 5 : Press (CTRL + F) from the keyboard and type "/head" and then search. ( If you are not understanding, see the below photo ) Step 6 : Now paste the below code just above the </head> tag. let's see code :   ➤ Code : mycode.js; Copy code ...