PHP 7.4 introduces type hints, which makes the PHP programming experience closer to languages like Java or C#, which is great! However, I found that I can't overload methods like I can in other typed language projects.
The solutions provided on Stack Overflow were not satisfactory, so I thought about how to overload methods in the most efficient and concise way, and created a support library for this. I wanted to share it with you because it might be the best solution you can find. You can get it on GitHub and learn more.
I think the short code snippet below is enough to understand how it works.
<code class="language-php">$userRepository = new UserRepository(); $userRepository->add('Micheal', 'Jordan', 23); $userRepository->add('Micheal Jordan', 23); $userRepository->add(new User("Micheal", "Jordan", 23)); $userRepository->add(new UserDto("Micheal", "Jordan", 23)); $userRepository->add(['fist_name' => 'Micheal', 'last_name' => 'Jordan', 'number' => 23]);</code>
<code class="language-php">public function add(mixed ...$args): void { $addMethodOverloader = MethodOverloader::create($this) ->register($this->addByFirstNameLastNameAndNumber(...), 'string', 'string', 'int') ->register($this->adddByUser(...), User::class) ->register($this->addByUserDto(...), UserDto::class) ->register($this->addByArray(...), 'array') ->register($this->addNyNameAndNumber(...), 'string', 'int') ->onFailure(function() { throw new MyCustomException(); }); $addMethodOverloader->invoke($args); }</code>
This is my first post, please tell me if it's ok. If you have any questions, please feel free to ask.
The above is the detailed content of Overloading methods with types in PHP and above. The way it should be.. For more information, please follow other related articles on the PHP Chinese website!