PHP two methods with the same name

前端 未结 4 949
借酒劲吻你
借酒劲吻你 2021-02-07 14:04

Can I have two methods sharing the same name, but with different arguments?

One would be public static and would take 2 arguments, the other one just public and takes on

4条回答
  •  伪装坚强ぢ
    2021-02-07 14:50

    I'm just giving you the super lazy option:

    function __call($name, $args) {
        $name = $name . "_" . implode("_", array_map("gettype", $args)));
        return call_user_func_array(array($this, $name), $args);
    }
    

    That would for example invoke the real function name getPrice_string_array for two parameters of that type. That's sort of what languages with real method signature overloading support would do behind the scenes.

    Even lazier would be just counting the arguments:

    function __callStatic($name, $args) {
        $name = $name . "_" . count($args);
        return call_user_func_array(array($this, $name), $args);
    }
    

    That would invoke getPrice_1 for 1 argument, or getPrice_2 for, you guessed it, two arguments. This might already suffice for most use cases. Of course you can combine both alternatives, or make it more clever by search for all alternative real method names.

    If you want to keep your API pretty and user-friendly implementing such elaborate workarounds is acceptable. Very much so.

提交回复
热议问题