BENderIsGr8te
3 years ago
255
0
Tips

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)
    {
        //logic
    }

    public function fooThree(Closure $closure)
    {
        //logic
    }

    public function fooLast(string $myString, array $attribute)
    {
        //logic
    }
}

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()
$bar->foo($thirdVar);

// Will map to $bar->fooThree()
$bar->foo($secondVar);

// Will map to $bar->foo1()
$bar->foo($firstVar);

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

// Will not map to anything
$bar->foo(true);

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.

https://gist.github.com/eckenroed/607bb62f569e7c00ced02002cfb19b39

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.