dongre6227 2011-04-22 13:35
浏览 60

检查是否设置了功能参数

I have a function that loads a butterfly image.

There are 3 possible parameters: colour, angle and position

The last one is always explicitly set, but the first 2, if not set, are determined with a random number. This means that the function will always load a nice randomly coloured and angled butterfly, unless specifically set.

I have this

function randombf ($randbf,$randangle,$position) {
    $randbf = rand(1,4);
    $randangle = rand(1,4);
    echo '<div class="bf '.$position.'" style="background:url(\'images/bf_'.$randangle.'_'.$randbf.'.png\');"></div>';
}

Now the problem I have is that I would only like the random to be set if the parameters aren't passed.

Something like:

if(!$randbf) {
    $randbf = rand(1,4);
}

But that doesn't work if I pass

randombf('1','2','whatever')

It performs the random regardless.

What am I doing wrong?

  • 写回答

2条回答 默认 最新

  • duangengruan2144 2011-04-22 13:40
    关注

    You should change the order of your parameters. Put position first because it will be always specified. If you do it this way, you will be able to write randombf(12) or randombf(12, 1, 2) or even randombf(12, 1).

    Omitted parameters will be set to null (you can specify anything else if you want, but only scalar values), so you only have to check if the var is_null().

    function randombf ($position, $randbf = null, $randangle = null) {
        if (is_null($randbf)) $randbf = rand(1,4);
        if (is_null($randangle)) $randangle = rand(1,4);
        echo '<div class="bf '.$position.'" style="background:url(\'images/bf_'.$randangle.'_'.$randbf.'.png\');"></div>';
    }
    

    Let me incorporate the link @Matt Ball has posted into my answer:

    Default function arguments

    评论

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改