函数带/不带传递参数-PHP


Function With/Without Passing an argument - PHP

下面是我为插入换行而创建的函数。

它像这样工作得很好;br(2)//任何数字,例如2。

然而,如果我只键入br(),我希望它能工作;它将使用1,但如果我指定一个数字,它将使用该数字。作为一个默认值,如果没有指定,我已经在谷歌上搜索过了,但找不到合适的单词来搜索,我想找不到答案。

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

您需要默认参数。也许只是:

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

您想要使用默认值:

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

参考:PHP手册-函数参数

添加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