|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
[2015-06-29 12:51 UTC] cmb@php.net
[2015-06-29 18:20 UTC] kalle@php.net
-Status: Open
+Status: Closed
-Assigned To:
+Assigned To: kalle
[2015-06-29 18:20 UTC] kalle@php.net
|
|||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Wed Oct 29 13:00:01 2025 UTC |
Description: ------------ Hello, Maybe this would finally reach someone's heart; as method overloading is really important to Object Oriented, especially now that PHP 7 will support type hinting for primitives. Imagine a StringBuilder class (which I'm really creating), now a StringBuilder builds a string by appending/prepending a string, any primitive type, another StringBuilder but not an object. class StringBuilder { public function append(StringBuilder $stringBuilder) { $this->string += $stringBuilder->toString(); } public function append(string $string) { $this->string += $string; } } This simply can't be achieved right now, and there's really no reason since would be allowed to hint in PHP7. One "get-around" solution right now is to use __call method to dispatch to distinct methods, this way it appears as if we are using one single method, but really we are using distinct methods. The problem is that 2 methods might have different arguments, so we have to use func_num_args() to distinguish which method to use, followed by a call_user_func_array : class Foo { private function doSomethingWith2Parameters($a, $b) { } private function doSomethingWith3Parameters($a, $b, $c) { } public function __call($method, $arguments) { if($method == 'doSomething') { if(count($arguments) == 2) { return call_user_func_array(array($this,'doSomethingWith2Parameters'), $arguments); } else if(count($arguments) == 3) { return call_user_func_array(array($this,'doSomethingWith3Parameters'), $arguments); } } } }