donte1234567 2013-07-29 04:47
浏览 12
已采纳

PHP函数使用变量中的旧值

So I have a stylesheet that i've written in PHP as well as a settings file that is included at the top of the stylesheet and holds some variables and functions that define some of my css properties. For example:

// Background color for body element
// Type: String
$bodyBGColor = 'rgb(67,142,169)';

// Has background Image for body element
// Type: Bool
$bodyBGIMG = false;

function hasBGIMG(){
    if($bodyBGIMG){
        echo "url(../img/".$adPrefix."_BG.png) !important";
    }else{
        echo " ";
    }
};

In the CSS I use the hasBGIMG() function.

body{
background-color: <?php echo $bodyBGColor.' !important' ?>;
background: <?php hasBGIMG(); ?>;
}

The first time I created and used the function it worked great, but when I change the value of $bodyBGIMG to true the CSS files still shows the value for false.

Here's the output in the css file:

body{
background-color: rgb(67,142,169) !important;
background:  ;
}

I have other functions in the file that behave the same way. I can even add new variables and functions to the file and they get parsed properly and yet any old functions keep their old values.

Any thoughts on why the function isn't looking at the updated variables or why the stylesheet is keeping the old values?

Thanks

  • 写回答

4条回答 默认 最新

  • duanmu2941 2013-07-29 04:50
    关注

    The variable $bodyBGIMG inside the function definition is local to the function (not global). Therefore, you must either call global $bodyBGIMG or pass it in as a function parameter:

    Solution using global variable:

    // Variable $hasBGIMG must be defined before the global keyword is called.
    function hasBGIMG(){
        global $bodyBGIMG;
        if($bodyBGIMG){
            echo "url(../img/".$adPrefix."_BG.png) !important";
        }else{
            echo " ";
        }
    };
    

    Solution with passing the value to the function:

    function hasBGIMG($bodyBGIMG){
        if($bodyBGIMG){
            echo "url(../img/".$adPrefix."_BG.png) !important";
        }else{
            echo " ";
        }
    };
    

    and later on:

    // Variable $bodyBGIMG must be defined before function hasBGIMG is called.
    background: <?php hasBGIMG($bodyBGIMG); ?>;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)