PHP两种同名方法 [英] PHP two methods with the same name

查看:64
本文介绍了PHP两种同名方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以有两个共享相同名称,但参数不同的方法吗?

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

一个将是公共静态的,将接受2个参数,另一个将是公共的,仅接受一个参数

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

示例

class product{

  protected
    $product_id;

  public function __construct($product_id){
    $this->product_id = $product_id;
  }

  public static function getPrice($product_id, $currency){
    ...
  }

  public function getPrice($currency){
    ...
  }

}

推荐答案

我只是给你超级懒惰的选择:

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);
}

例如,这将为该类型的两个参数调用实函数名称 getPrice_string_array .那种具有真实方法签名重载支持的语言会在后台做些什么.

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);
}

这将为一个参数调用 getPrice_1 ,或者为两个参数调用 getPrice_2 .对于大多数用例,这可能已经足够了.当然,您可以结合使用这两种替代方法,或者通过搜索所有替代的真实方法名称来使其更加聪明.

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.

如果您想保持API的美观和用户友好性,则可以采用这种精心设计的变通办法.非常非常.

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

这篇关于PHP两种同名方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆