开发者

PHP 5.3 method overloading (like in Java)

In Java, we have a method overloading feature that's very useful for Singletons. For example, i have two different getInstance methods, public static, that behave differently based on the parameters received:

public static Currency getInstance(String currencyCode)
public static Currency getIn开发者_如何学编程stance(Locale locale)

Can we do this in PHP?


You can determine the argument type at run-time:

function getInstance($currency) {
   if (is_string($currency)) {
      $currency = lookupLokale($currency);
   }
   // do something with the $currency object
}

In php5.3+ (php5.0+ for non-static methods), you can also use php's method overloading to implement Java-like semantics yourself. However, OOP overloading is likely to produce messy code, and you should prefer the above in-method solution.

In most cases, it's clearer if you just use two different method names.


Come on, at least try to Google :). Theres excellent documentation about this. For example on the PHP site ITSELF:

EDIT: New link that describes method overloading

http://www.dinke.net/blog/en/2007/08/01/method-overloading-in-php5/

Now I got the same kind of overloading.


Directly PHP don't supports method overloading, but we can implement this feature with func_get_args():

class Obj
{
    function __construct() {

        $args = func_get_args();

        if (count($args) != 2) {
            echo ("Must be passed two arguments !\n");
            return;
        }

        if (is_numeric($args[0]) && is_numeric($args[1])) {
            $result = $this->_addnum($args[0], $args[1]);
        }
        else if (is_string($args[0]) && is_string($args[1])) {
            $result = $this->_addstring($args[0], $args[1]);
        }
        else if (is_bool($args[0]) && is_bool($args[1])) {
            $result = $this->_addbool($args[0], $args[1]);
        }
        else if (is_array($args[0]) && is_array($args[1])) {
            $result = $this->_addarray($args[0], $args[1]);
        }
        else {
            echo ("Argument(s) type is not supported !\n");
            return;
        }

        echo "\n";
        var_dump($result);
    }

    private function _addnum($x, $y) {return $x + $y;}

    private function _addstring($x, $y) {return $x . $y;}

    private function _addbool($x, $y) {return $x xor $y;}

    private function _addarray($x, $y) {return array_merge($x,$y);}
}

// invalid constructor cases
new Obj();
new Obj(null, null);

// valid ones
new Obj(2,3);
new Obj('A','B');
new Obj(false, true);
new Obj([3], [4]);

Outputs :

Must be passed two arguments !
Argument(s) type is not supported !

int(5)
string(2) "AB"
bool(true)
array(2) {
  [0] =>
  int(3)
  [1] =>
  int(4)
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜