DEV Community

Cover image for Overloading methods with types in PHP 8.0 and above. The way it should be.
michalczerski
michalczerski

Posted on

Overloading methods with types in PHP 8.0 and above. The way it should be.

Since PHP 7.4 we have types and I have feeling I was programming in languages like Java or C# which is really nice but then I noticed I can’t overload my methods way I used to in other projects with typed languages.

Solutions given on StackOverflow are unacceptable so I was thinking how to overload methods in most efficient and clean way and made library to support it. I want to share it with you because it’s best You could find. You can get it on GitHub and learn more.

I think short snippet of code beneath is sufficient to understand how does it work.

$userRepository = new UserRepository();
$userRepository->add('Micheal', 'Jordan', 23);
$userRepository->add('Micheal Jordan', 23);
$userRepository->add(new User("Micheal", "Jordan", 23));
$userRepository->add(new Player("Micheal", "Jordan", 23));
$userRepository->add(['fist_name' => 'Micheal', 'last_name' => 'Jordan', 'number' => 23]);
Enter fullscreen mode Exit fullscreen mode
public function add(mixed ...$args): void
{
        $addMethodOverloader = MethodOverloader::create($this)
        ->register($this->addByFirstNameLastNameAndNumber(...),'string', 'string', 'int')
        ->register($this->adddByUser(...), User::class)
        ->register($this->addByPlayer(...), Player::class)
        ->register($this->addByArray(...), 'array')
        ->register($this->addNyNameAndNumber(...), 'string', 'int')
        ->onFailure(function() {
            throw new MyCustomException();
        });

    $addMethodOverloader->invoke($args);
}
Enter fullscreen mode Exit fullscreen mode

It's my first post so please let me know if it's ok. If you have any questions feel free to ask.

Top comments (2)

Collapse
 
xwero profile image
david duymelinck • Edited

I tend to follow the python mantra to make code explicit. So in my view overloading methods is a design failure, because it makes the input of a method more opaque.

If you have data that has multiple forms use a DTO to handle the conversion, and use the DTO as method input.

A tip for the code blocks, add php after the first ticks, this Will highlight the code. Making it more readable.

Collapse
 
michalczerski profile image
michalczerski

I was thinking about example how to show possibility of overloading 2 custom user class by type. Thank you for your feedback.