PHP two methods with the same name

前端 未结 4 959
借酒劲吻你
借酒劲吻你 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:54

    You could, kind of... I consider it very much "hack" solutions, but you could make a single function and assign a standard value, that wouldn't otherwise be okay to use, to the parameters as needed. Then if you do not pass the function a certain parameter, it will be set to fx "-1".

    public function getPrice($product_id = "-1", $currency) {
        if($product_id = "-1") {
            //do something
        }else {
            //do something
        }
    }
    

    Or if you really need one method to be static, you can make a method that evaluates which method to call and call that instead of your getPrice:

    public function whichGetPrice($product_id = "-1", $currency) {
        if($product !== "-1") {
            getStaticPrice($product_id, $currency);
        }else {
            getPrice($currency);
        }
    }
    

    Like I said, very much "hack" solutions. It's not exactly pretty, nor a way people would expect you to do it. So I wouldn't necessarily recommend it, but it can help you do what you want.

提交回复
热议问题