Method Overloading in PHP5

Although with release of PHP5 we finaly got some long awaited OOP features, sometimes I really miss overloading capability which exists in languages like Java. I am talking about something like this:

class Overloading_Test
{
  public void hello()
  {
    System.out.println("Hello Anonymous");
  }

  public void hello(String name)
  {
    System.out.println("Hello " + name);
  }


  public void hello(String firstName, String lastName)
  {
    System.out.println("Hello " + firstName + " " + lastName);
  }
}

This way you can call either hello with no arguments at all, or with one or two arguments, and proper method would always be called. Unfortunately, if you try something like this in PHP, it would give you fatal error, because basically, methods cannot be redeclared, since support for overloading is not part of core language like in Java.

However, there is still a way to achieve this Java like overloading functionality by using “magic” methods that are described in PHP Manual. Although it is not clear from manual how could you achieve exact functionality like in Java, I played a little bit with __call function, and get interesting workaround.

<?php

class Overloading_Test
{
  function __call($method_name, $arguments)
  {
    //list of supported methods
    //only 'hello' for this test
    $accepted_methods = array("hello");

    //in case of unexistant method we trigger fatal error
    if(!in_array($method_name, $accepted_methods))
    {
      trigger_error("Method <strong>$method_name</strong> doesn't exist", E_USER_ERROR);
    }

    //we inspect number of arguments
    if(count($arguments) == 0)
    {
      $this->hello1();
    }
    elseif(count($arguments) == 1)
    {
      $this->hello2($arguments[0]);
    }
    elseif(count($arguments) == 2)
    {
      $this->hello3($arguments[0], $arguments[1]);
    }
    else
    {
      return false;
    }
  }

  function hello1()
  {
    echo "Hello Anonymous<br>";
  }

  function hello2($name)
  {
    echo "Hello $name<br>";
  }

  function hello3($first_name, $last_name)
  {
    echo "Hello $first_name, $last_name<br>";
  }
}


$ot = new Overloading_Test();
$ot->hello();
$ot->hello("John");
$ot->hello("John", "Smith");
//this one will produce fatal error
//$ot->test();
?>

If you run this code, you will get something like:

Hello Anonymous
Hello John
Hello John, Smith

So, what is going on here? Whenever we call some undeclared method (which is the case with ‘hello’ method here), magic method __call is called, and two arguments (method name and arguments) are passed to it. For this simple test, we only support overloading of ‘hello’ method, so in case you try any other, we trigger fatal error.

What’s going on further is, we simple check number of argumens passed (by counting $arguments array), and call proper method. For the sake of clarity, I only used simple overloading based on number of arguments, but you could also check for argument type (ie string, integer etc.) and call proper method.

So, as you see, method overloading in PHP5 is not as elegant as in Java, but you can still make it. For more information about ‘magic’ fucntions (there are quite a few for member overloading as well), please visit PHP Manual.

Comments

  1. February 21st, 2017 | 9:26 am
  2. February 21st, 2017 | 9:33 am
  3. February 21st, 2017 | 9:54 am
  4. February 22nd, 2017 | 1:25 pm

    Sorry, I’m busy at the moment buy cheap aripiprazole Republicans — many of whom have spent the past 12 months hammering the administration over its handling, or mishandling, of the Benghazi affair — walked a fine line with their statements Wednesday, raising questions about last year’s attack without politicking on what has become one of America’s most solemn days.

  5. February 22nd, 2017 | 2:03 pm

    Insufficient funds cheap alternative to abilify His No. 34 jersey is the only one worn by a Rangers player to be retired, and there is a statue of the pitcher at Rangers Ballpark. He is the only player in the Hall of Fame whose bust is topped by a Texas cap.

  6. February 22nd, 2017 | 3:55 pm

    I’d like to apply for this job cheaper version of abilify On top of that it will also publish its first economic forecasts for 2016 and the stronger the picture the harder it will be to persuade markets that any future rise in interest rates will only be slow and measured.

  7. February 22nd, 2017 | 9:47 pm
  8. February 22nd, 2017 | 9:56 pm
  9. February 22nd, 2017 | 10:05 pm
  10. February 25th, 2017 | 2:39 pm

    What’s up, just wanted to say, I liked this post.
    It was inspiring. Keep on posting!

  11. February 25th, 2017 | 7:25 pm

    Certainly, while pure astaxanthin is still the
    biggest seller for Cyanotech’s Nutrex supplements arm, an enhancing percentage of earnings now
    originates from condition-specific finished items under the MD
    Formulas brand, says the company, which posted a 46% hike in incomes
    in fiscal year 2012 to $24.63 m and also a 110% rise in earnings to $3.6 m.

    Also visit my weblog: biosphere nutrition

  12. February 25th, 2017 | 9:54 pm

    It is truly a great and useful piece of information. I’m satisfied that you simply shared this useful information with us.
    Please stay us up to date like this. Thank you for sharing.

  13. February 26th, 2017 | 1:27 pm

    Can I call you back? buy cardura xl The Chinese government has also made clear it’s well aware of Apple – though not always in a good way. In April, state media bashed Apple for its “arrogance,” protesting among other things that its current 1-year service warranty was insufficient. Apple initially dismissed those criticisms, but Cook later apologized to Chinese consumers.

  14. February 26th, 2017 | 3:07 pm

    I’d like to change some money chance greatest prednisolone generique solupred mall Such was the case 35 years ago when I was a casualty officer. If anyone managed to get past the reception staff with, for example, a sore throat, they were shown the door. It was explained that the department was not an alternative to a GP practice, and that I, as a surgical trainee, was not a GP.

  15. February 27th, 2017 | 4:12 am

    I really like what you guys are usually up too. Such clever work
    and exposure! Keep up the amazing works guys I’ve added you guys to
    my own blogroll.

Leave a reply