doudun3910 2011-04-30 21:27
浏览 52
已采纳

如何将(可选)参数传递给用户定义的函数?

I mean, how do you pass your arguments to a function?

Do your user function call looks like this:

$this->getSomeNumber($firstArg, $secondArg, null);

or do you detect how many arguments was passed to the function and then do the job?

I wonder if is there any coding style covering this. And how do other programming languages handle this?

UPDATE

Example fot those, who not understand:

function doSmth($firstArgument) {
    if(func_num_args() > 1) {
        //do job if second argument was passed
    }
}

Second example:

function doSmthElse($firstArgument, $secondArgument) {
    if($secondArgument) {
        //do job if second argument was passed
    }
}

And then you call it like:

doSmth($var, $secondvar) or doSmth($var)

//**OR**

doSmthElse($var, $secondvar) or doSmthElse($var, null)

Which is better to use? I mean which do other programmers expect from you?

  • 写回答

2条回答 默认 最新

  • douzhang7603 2011-04-30 21:59
    关注

    If the argument is optional, specify it normally with a default value:

    function foo($requiredArg, $optionalArg = null)
    

    If the function takes multiple optional arguments, specify them explicitly like in the above example.

    If the function takes a variable number of arguments (for example, such as sprintf), then use func_get_args & co.

    /**
     * Specify here as a comment that this function takes a variable amount of args
     */
    function doSomethingWithParameters() {
        ...
    }
    

    If the function takes required parameters and a variable amount of parameters, the same approach applies: Specify always required parameters explicitly like in the first example.

    Using comments to clarify variable args etc. is always a good idea. It might be an even better idea to use an array instead, but this would probably depend on what you're doing.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序