PHP有两个同名的方法

时间:2011-12-07 01:08:29

标签: php class methods

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

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

}

4 个答案:

答案 0 :(得分:11)

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

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

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

答案 1 :(得分:5)

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

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

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

即使更懒惰也只是计算论点:

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

那会为{1}}调用1 getPrice_1,或者getPrice_2,你猜对了,两个参数。对于大多数用例来说,这已经足够了。当然,您可以将两种选择结合起来,或者通过搜索所有其他实际方法名称来使其更加聪明。

如果您希望保持API漂亮且用户友好,那么实施这些精心设计的解决方法是可以接受的。非常如此。

答案 2 :(得分:1)

PHP目前不支持以已知方式进行重载,但您仍然可以通过使用魔术方法来实现目标。

从PHP5手册:overloading

答案 3 :(得分:0)

你可以,有点...... 我认为这是非常“破解”的解决方案,但你可以制作一个单独的功能,并根据需要为参数分配一个标准值,否则就无法使用。然后,如果您没有将函数传递给某个参数,它将被设置为fx“-1”。

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

或者如果你真的需要一个静态的方法,你可以创建一个方法来评估调用哪个方法并调用那个而不是你的getPrice:

public function whichGetPrice($product_id = "-1", $currency) {
    if($product !== "-1") {
        getStaticPrice($product_id, $currency);
    }else {
        getPrice($currency);
    }
}
像我说的那样,非常“黑客”的解决方案。它不是很漂亮,也不是人们期望你这样做的方式。所以我不一定会推荐它,但它可以帮助你做你想做的事。