PHP有两个同名的方法

Ale*_*lex 14 php methods class

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

一个是public static,需要2个参数,另一个只是public,只需要一个参数

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){
    ...
  }

}
Run Code Online (Sandbox Code Playgroud)

ETo*_*reo 11

不.PHP不支持经典重载.(它确实实现了一些称为重载的东西.)

您可以使用func_get_args()及其相关函数获得相同的结果:

function ech()
{
  $a = func_get_args();
  for( $t=0;$t<count($a); $t++ )
  {
    echo $a[$t];
  }
}
Run Code Online (Sandbox Code Playgroud)


mar*_*rio 6

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

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

例如,这将为该getPrice_string_array类型的两个参数调用实际函数名称.那种具有真正方法签名重载支持的语言将在幕后进行.

甚至更懒惰的只是计算论点:

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

这会引发getPrice_1一个参数,或者getPrice_2你猜对了两个参数.对于大多数用例来说,这已经足够了.当然,您可以结合两种选择,或通过搜索所有替代实际方法名称使其更加聪明.

如果你想保持你的API漂亮和用户友好实现这样精细的解决方案是可以接受的.非常如此.