【问题标题】:PHP class function namingPHP类函数命名
【发布时间】:2012-04-20 15:19:56
【问题描述】:

我在命名函数时遇到问题。我有一门课,我需要 2 个函数,如下所示。

class myclass {
    public function tempclass () {
        echo "default";   
    }
    public function tempclass ( $text ) {
        echo $text;
    }
}

当我打电话时

tempclass('testing'); // ( called after creating the object )

function tempclass() 正在被调用,我如何才能拥有 2 个名称相同但参数不同的函数?

【问题讨论】:

  • 为什么你的代码使用引号格式而不是代码格式?

标签: php class function naming


【解决方案1】:

传统的重载目前在 PHP 中是不可能的。相反,您需要检查传递的参数,并确定您希望如何响应。

此时查看func_num_argsfunc_get_args。您可以在内部使用这两种方法来确定您应该如何响应某些方法的调用。例如,在您的情况下,您可以执行以下操作:

public function tempclass () {
  switch ( func_num_args() ) {
    case 0:
      /* Do something */
      break;
    case 1:
      /* Do something else */
  }
}

或者,您也可以为您的参数提供默认值,并使用这些值来确定您应该如何反应:

public function tempclass ( $text = false ) {
  if ( $text ) {
    /* This method was provided with text */ 
  } else {
    /* This method was not invoked with text */
  }
}

【讨论】:

  • +1,但建议编辑您的答案以包含指向 func_get_args()func_num_args() 的参考链接。 :-)
【解决方案2】:

在 PHP 中不能重载。

但是,对于您上面的简单示例,这样的事情会起作用:

class myclass {
    public function tempclass ($text='Default') {
        echo $text;
    }
}

【讨论】:

  • 进行了我认为您可能同意的更改。
  • 完全!没想到=)
  • 您的在线联系表格不起作用。你住在苏格兰,我也是。我的联系方式可以通过这个视线获得。
猜你喜欢
  • 2015-11-05
  • 1970-01-01
  • 1970-01-01
  • 2016-12-13
  • 2018-08-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多