Req #69961 [Opn]: Method overloading with PHP 7
| From: | cmb@php.net | Date: | Mon, 29 Jun 2015 12:51:37 +0000 |
| Subject: | Req #69961 [Opn]: Method overloading with PHP 7 | ||
| References: | 1 | Groups: | php.bugs |
| Request: | Send a blank email to php-bugs+get-193991@lists.php.net to get a copy of this message | ||
Edit report at https://bugs.php.net/bug.php?id=69961&edit=1
ID: 69961
Updated by: cmb@php.net
Reported by: simobj at live dot com
Summary: Method overloading with PHP 7
Status: Open
Type: Feature/Change Request
Package: SPL related
Operating System: Linux
PHP Version: 7.0.0alpha2
Block user comment: N
Private report: N
New Comment:
This is unlikely to be implemented, see request #40979 and
<http://marc.info/?l=php-internals&m=121397217528280&w=2>.
Previous Comments:
------------------------------------------------------------------------
[2015-06-29 10:16:43] simobj at live dot com
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);
}
}
}
}
------------------------------------------------------------------------
--
Edit this bug report at https://bugs.php.net/bug.php?id=69961&edit=1