函数 With/Without 传递参数 - PHP

Function With/Without Passing an argument - PHP

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

这样很好用; br(2); //任何数字,例如2。

但是,如果我只输入 br();,我希望它能正常工作;它将使用 1,但如果我指定一个数字,它将使用该数字。如果指定了 none,则可以作为默认值,我查看了整个 google,但找不到合适的词来搜索并找到我想的答案。

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

您想使用默认值:

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

参考:PHP Manual - Function arguments

默认加1

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

你可以试试这个:

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

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

你想要Default Parameters。也许只是:

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