3 years ago

PHP Overloading Trait

Posted 3 years ago by BENderIsGr8te

I was catching up on the Laravel Podcast from late last year and heard them discussing Adam Wathan's Overloadable Trait.

I have something I had been working on that simulates overloading. I thought I would share it since I just created it on GitHub.

Essentially, you use a naming and definition convention.

class Bar {
    use Overloader;

    public function foo1(array $array)
        // logic

    public function foo2(string $string)

    public function fooThree(Closure $closure)

    public function fooLast(string $myString, array $attribute)

Now when working with your API, you can call foo method and just pass in your argument and the Overloader will map to the proper function.

$firstVar = ['item', 'another'];
$secondVar = function(){ return 1;};
$thirdVar = 'Hello World';

$bar = new Bar;

// Will map to $bar->foo2()

// Will map to $bar->fooThree()

// Will map to $bar->foo1()

// Will map to $bar->fooLast()
$bar->foo('hello world', ['item']);

// Will not map to anything

The Overloader will look for any method names that start with method called (in this case foo. Then it will call any functions that have the exact same signature.

I'm sure there is room for improvement, so I thought I would share it.

I should note that if you use __call() method in your class, the trait will look for a match first before passing it to the call method in your class. I wrote this trait and tested it as part of a Laravel Model, so all of Laravel's magic methods still work.

Please sign in or create an account to participate in this conversation.