开发者

PHP function is not working

开发者 https://www.devze.com 2023-04-11 15:41 出处:网络
I\'m just trying to write a function that can switch background color. Each time it\'s run, it should return the other color, but it\'s not working

I'm just trying to write a function that can switch background color.

Each time it's run, it should return the other color, but it's not working

function bgcolour_switch(){
    if(!isset($p)){
        global $p;
        $p = "#C0C0C0";
        return $p;
    }else{
        if($p == "#C0C0C0"){
            $p = "#FFFFFF";
            return $p;
        }elseif($p == "#FFFFFF"){
            $p = "#C0C0C0";
            return $p;
        }
    }
}

I keep getting the same colo开发者_如何转开发r returned (#C0C0C0)


Well, $p is never initially set in the scope of your function, so the if statement always evaluates to true.

Try moving the global $p; line to the beginning of the function, before the if statement.


$p is a local variable. Its scope is the function itself. Each time you call this function, it is reset, so isset($p) on the first line, will never evaluate to true.

If $p is a global variable, add the next line at the start of your function (above the if).

global $p;

You could write your code a little shorter too. It can be much shorter even, but in this way it's still readable for you.

function bgcolour_switch(){
  global $p;
  if(!isset($p) || $p === "#FFFFFF")
    $p = "#C0C0C0";
  else
    $p = "#FFFFFF";
  return $p;
}


Call global before you check for $p to exist. Try this (untested):

<?php
function bgcolour_switch(){
    global $p;
    if(!isset($p)){
        $p = "#C0C0C0";
        return $p;
    }else{
        if($p == "#C0C0C0"){
            $p = "#FFFFFF";
            return $p;
        }elseif($p == "#FFFFFF"){
            $p = "#C0C0C0";
            return $p;
        }
    }
}


Have the function require $p

function fname($p = null){
//such and such..
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号