Every two weeks I send out a newsletter containing lots of interesting stuff for the modern PHP developer. You can expect quick tips, links to interesting tutorials, opinions and packages. Want to learn the cool stuff? Then sign up now!

Method overloading is possible in PHP (sort of)

PHP does not support method overloading. In case you’ve never heard of method overloading, it means that the language can pick a method based on which parameters you’re using to call it. This is possible in many other programming languages like Java, C++.

So, under normal circumstances, you can’t do this in PHP:

class Foo
{
   function bar(A $baz)
   {
      ...
   }

   function bar(B $baz)
   {
      ...
   }
}

However, with some clever coding, Adam Wathan made a trait, aptly called Overloadable, that makes method overloading possible. It works by just accepting any parameters using the splat operator and then determining which of the given functions must be called according to the given parameters.

Let’s rewrite that example above using the Overloadable trait.

class Foo
{
    use Overloadable;

    function bar(...$arguments)
    {
        return $this->overload($arguments, [
            function (A $baz) {
               $this->functionThatProcessesObjectA($baz);
            },
            function (B $baz) {
               $this->functionThatProcessesObjectB($baz);
            },
        ]);
    }
}

Pretty cool stuff. In a gist on GitHub Adam shares a couple of examples, the source code of the trait and the tests that go along with it. Check it out!

https://gist.github.com/adamwathan/120f5acb69ba84e3fa911437242796c3

Freek Van der Herten is a partner and developer at Spatie, an Antwerp based company that specializes in creating web apps with Laravel. After hours he writes about modern PHP and Laravel on this blog. When not coding he’s probably rehearsing with his kraut rock band.
  • While I’d love PHP to have method overloading, this implementation has “bad idea” written all over it 🙂 Not supported by IDEs, not particularly performant, makes it difficult to figure out which code path gets executed by a specific call.

    It’s a nice hack though, reminds me of my implementation of JS-like dynamic methods (via __set and __call).

    • Yea, I probably wouldn’t use this in a production environment. But, like you said, it’s a nice hack and kinda cool that it can work.

  • Nathan King

    Cool as hell, would love overloading as a native feature, but I would never ever recommend or use this. Neat hack though!