【问题标题】:How do you create optional arguments in php?如何在 php 中创建可选参数?
【发布时间】:2010-09-07 06:50:35
【问题描述】:

在 PHP 手册中,为了显示带有可选参数的函数的语法,它们在每组依赖的可选参数周围使用括号。例如,对于date() 函数,手册中写道:

string date ( string $format [, int $timestamp = time() ] )

其中$timestamp 是可选参数,留空时默认为time() 函数的返回值。

在 PHP 中定义自定义函数时如何创建这样的可选参数?

【问题讨论】:

    标签: php


    【解决方案1】:

    与手册非常相似,在参数定义中使用等号 (=):

    function dosomething($var1, $var2, $var3 = 'somevalue'){
        // Rest of function here...
    }
    

    【讨论】:

    • function dosomething($var1, $var2, $optionalValue = null) 我找到了更好的选择。
    【解决方案2】:

    参数的默认值必须是常量表达式。它不能是变量或函数调用。

    如果您需要此功能:

    function foo($foo, $bar = false)
    {
        if(!$bar)
        {
            $bar = $foo;
        }
    }
    

    当然,假设 $bar 不应该是布尔值。

    【讨论】:

    • 但是,这将评估是否将 0 或 "false" 传递给 $bar。
    • Null 是一个更好的默认值。
    • @DooMMasteR,在这里,您的意思是$bar === false - 这是当$bar 默认为false 时应该执行的操作。如果传入0,这将避免不正确的操作,因此它确实有效 - 除非需要布尔值。正如 Kzqai 所说,更通用的解决方案是使用$bar = null,因为当 $bar 的值为布尔值时也可以使用它。然后测试变为if (is_null($bar))if ($bar === null)
    【解决方案3】:

    一些我也觉得有用的笔记:

    • 将默认值保留在右侧。

      function whatever($var1, $var2, $var3="constant", $var4="another")
      
    • 参数的默认值必须是常量表达式。它不能是变量或函数调用。

    【讨论】:

      【解决方案4】:

      给可选参数一个默认值。

      function date ($format, $timestamp='') {
      }
      

      【讨论】:

        【解决方案5】:

        日期函数的定义如下:

        function date($format, $timestamp = null)
        {
            if ($timestamp === null) {
                $timestamp = time();
            }
        
            // Format the timestamp according to $format
        }
        

        通常,你会这样设置默认值:

        function foo($required, $optional = 42)
        {
            // This function can be passed one or more arguments
        }
        

        但是,只有 literals 是有效的默认参数,这就是为什么我在第一个示例中使用 null 作为默认参数,不是 $timestamp = time(),并将其组合起来带有空检查。文字包括数组(array()[])、布尔值、数字、字符串和 null

        【讨论】:

          【解决方案6】:

          如果不知道需要处理多少个属性,可以使用 PHP 5.6 (see full documentation here) 中引入的可变参数列表令牌(...)。

          语法:

          function <functionName> ([<type> ]...<$paramName>) {}
          

          例如:

          function someVariadricFunc(...$arguments) {
            foreach ($arguments as $arg) {
              // do some stuff with $arg...
            }
          }
          
          someVariadricFunc();           // an empty array going to be passed
          someVariadricFunc('apple');    // provides a one-element array
          someVariadricFunc('apple', 'pear', 'orange', 'banana');
          

          如您所见,这个标记基本上将所有参数转换为一个数组,您可以以任何您喜欢的方式对其进行处理。

          【讨论】:

            【解决方案7】:

            从 7.1 开始,有一个可空参数的类型提示

            function func(?Object $object) {}
            

            它适用于这些情况:

            func(null); //as nullable parameter
            func(new Object());  // as parameter of declared  type
            

            但是对于可选值签名应该是这样的。

            function func(Object $object = null) {} // In case of objects
            function func(?Object $object = null) {} // or the same with nullable parameter
            
            function func(string $object = '') {} // In case of scalar type - string, with string value as default value
            function func(string $object = null) {} // In case of scalar type - string, with null as default value
            function func(?string $object = '') {} // or the same with nullable parameter
            
            function func(int $object = 0) {} // In case of scalar type - integer, with integer value as default value
            function func(int $object = null) {} // In case of scalar type - integer, with null as default value
            function func(?int $object = 0) {} // or the same with nullable parameter
            

            比它可以被调用为  

            func(); // as optional parameter
            func(null); // as nullable parameter
            func(new Object()); // as parameter of declared type
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2013-07-16
              • 1970-01-01
              • 1970-01-01
              • 2015-04-27
              • 2016-06-13
              • 2010-11-14
              • 1970-01-01
              • 2012-03-21
              相关资源
              最近更新 更多