【问题标题】:Function With/Without Passing an argument - PHP带/不带参数的函数 - PHP
【发布时间】:2015-04-26 18:26:10
【问题描述】:

下面是我创建的用于插入折线的函数。

这样可以正常工作; br(2); //任意数字,以2为例。

但是,如果我只输入 br();,我希望它能够工作。它将使用 1,但如果我指定一个数字,它将使用它。如果未指定任何默认值,则排序为默认值,我查看了整个谷歌,但找不到合适的词来搜索并找到我想的答案。

function br($i) {
    $j = 0;
    while ($j <= $i) {
        echo '<br />';
        $j++;
    }
}

【问题讨论】:

  • str_repeat('&lt;br&gt;', $i)
  • @JayBlanchard 什么...没有浓缩咖啡? 哼!
  • 如果你喜欢@Fred-ii-,你可以喝浓缩咖啡。我自己不是卡布奇诺迷。
  • @JonathanLaBerge 请阅读how to accept an answer并在下方做出选择。

标签: php function parameters null arguments


【解决方案1】:

你想要Default Parameters。也许只是:

function br($i=1) {
    echo str_repeat('<br />', $i);
}

【讨论】:

    【解决方案2】:

    你可以试试这个:

    function br($count = 1)
    {
        while($count) {
            echo '<br />';
            $count--;
        }
    }
    

    “$count = 1”部分将 $count 指定为可选参数。 http://php.net/manual/en/functions.arguments.php#functions.arguments.default

    【讨论】:

      【解决方案3】:

      添加 1 作为默认值

      function br($i = 1) {
          $j = 0;
          while ($j <= $i) {
              echo '<br />';
              $j++;
          }
      }
      

      【讨论】:

        【解决方案4】:

        您想使用默认值:

        function br($i = 1) {
            $j = 0;
            while ($j <= $i) {
                echo '<br />';
                $j++;
            }
        }
        

        参考:PHP Manual - Function arguments

        【讨论】:

        • 这很好用,谢谢。我是编程新手,没有意识到我可以这样做,但应该尝试过。谢谢。
        猜你喜欢
        • 1970-01-01
        • 2012-12-03
        • 2011-08-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-04-18
        相关资源
        最近更新 更多