【问题标题】:PHP 5.3 method overloading (like in Java)PHP 5.3 方法重载(如在 Java 中)
【发布时间】:2011-07-05 12:22:16
【问题描述】:

在 Java 中,我们有一个方法重载功能,这对单例非常有用。例如,我有两种不同的 getInstance 方法,即 public static,它们根据接收到的参数表现不同:

public static Currency getInstance(String currencyCode)
public static Currency getInstance(Locale locale)

我们可以在 PHP 中做到这一点吗?

【问题讨论】:

标签: php


【解决方案1】:

您可以在运行时确定参数类型:

function getInstance($currency) {
   if (is_string($currency)) {
      $currency = lookupLokale($currency);
   }
   // do something with the $currency object
}

在php5.3+(php5.0+为非静态方法),也可以使用php的method overloading自己实现类Java语义。但是,OOP 重载可能会产生混乱的代码,您应该更喜欢上面的方法内解决方案。

在大多数情况下,如果您只使用两个不同的方法名称会更清楚。

【讨论】:

  • 我了解获得相同行为的技巧,我正在使用它们。我只是想也许有更好的方法。
  • @Jomezxn 当您尝试将特定语言的概念从一种语言映射到另一种语言时,您问错了问题。
【解决方案2】:

来吧,至少尝试谷歌:)。有关于此的优秀文档。 例如在 PHP 网站 ITSELF:

编辑:描述方法重载的新链接

http://www.dinke.net/blog/en/2007/08/01/method-overloading-in-php5/

现在我得到了同样的重载。

【讨论】:

  • 不过,这与 OP 想要的重载类型不太一样。
  • 另一种选择是使用func_get_args(),然后根据它们的类型调用拟合实现。但不像 Java 或 .Net 那样具体。
  • 我真正的意思是重载,因为有多个同名但参数不同的函数。我刚刚阅读了该页面,而 php 只是指的是同名的不同内容... PHP 中的 OOP 实在是太糟糕了... 编辑:找到了一篇讨论正确类型重载的互联网帖子。
【解决方案3】:

直接PHP不支持方法重载,但是我们可以用func_get_args()实现这个功能:

class Obj
{
    function __construct() {

        $args = func_get_args();

        if (count($args) != 2) {
            echo ("Must be passed two arguments !\n");
            return;
        }

        if (is_numeric($args[0]) && is_numeric($args[1])) {
            $result = $this->_addnum($args[0], $args[1]);
        }
        else if (is_string($args[0]) && is_string($args[1])) {
            $result = $this->_addstring($args[0], $args[1]);
        }
        else if (is_bool($args[0]) && is_bool($args[1])) {
            $result = $this->_addbool($args[0], $args[1]);
        }
        else if (is_array($args[0]) && is_array($args[1])) {
            $result = $this->_addarray($args[0], $args[1]);
        }
        else {
            echo ("Argument(s) type is not supported !\n");
            return;
        }

        echo "\n";
        var_dump($result);
    }

    private function _addnum($x, $y) {return $x + $y;}

    private function _addstring($x, $y) {return $x . $y;}

    private function _addbool($x, $y) {return $x xor $y;}

    private function _addarray($x, $y) {return array_merge($x,$y);}
}

// invalid constructor cases
new Obj();
new Obj(null, null);

// valid ones
new Obj(2,3);
new Obj('A','B');
new Obj(false, true);
new Obj([3], [4]);

输出:

必须传递两个参数! 不支持参数类型! 整数(5) 字符串(2)“AB” 布尔(真) 数组(2){ [0] => 整数(3) [1] => 整数(4) }

【讨论】:

    猜你喜欢
    • 2010-10-27
    • 1970-01-01
    • 2014-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-01
    • 1970-01-01
    相关资源
    最近更新 更多