douqiu0796 2015-01-13 13:30
浏览 60
已采纳

在html源代码中回显全局变量

I have two global variables declared in my config.php file, I would like to call one of these depending on results from another page however I need some help with my syntax.

It simply add a class to the button (btn-success or btn-default)

config.php

define("BTN_SUCCESS", "btn-success");
define("BTN_DEFAULT", "btn-default");

I want to do something like the following but it doesn't work it simply prints out the names in my html source;

echo '<td>
<button id="fav" type="button" class="btn '.BTN_SUCCESS. || 'BTN_DEFAULT''"></button>
</td>';

If I insert either of them individually they work but it's not what I want, for example;

echo '<td>
<button id="fav" type="button" class="btn '.BTN_SUCCESS.'"></button>
</td>';

I want an or operator in there - is this possible? It's probably something simple. Quite new to php so any help is appreciated.

  • 写回答

2条回答 默认 最新

  • dongtanzhu5417 2015-01-13 13:32
    关注

    Try this

    echo '<td>
    <button id="fav" type="button" class="btn '.(BTN_SUCCESS?:BTN_DEFAULT).'"></button>
    </td>';
    

    The parenthesis is shorthand for

    if(BTN_SUCCESS) 
        echo BTN_SUCCESS;
     else
        echo BTN_DEFAULT;
    

    The if-condition above can be shortened using ternary operators:

    echo BTN_SUCCESS ? BTN_SUCCESS : BTN_DEFAULT;
    

    And if you want to echo the value of the condition (in this case BTN_SUCCESS) if it's truthful you can shorten it even more by removing the middle part (as of PHP 5.3):

    echo BTN_SUCCESS ?: BTN_DEFAULT;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 找驱动QTR2774-SU-IBM版本驱动
  • ¥15 NeRF的代码复现以及人工智能入门
  • ¥15 centos如何做一个可以让ikuai连接的openvpn
  • ¥15 Protege 中的Entities下面的界面删除了如何复原
  • ¥15 scrapy爬虫求帮
  • ¥15 imageEnView绘图问题
  • ¥15 关于#python#的问题:您好可以加您一下联系方式吗,在复现的时候确实有点问题难以解决
  • ¥15 联想电脑重装系统时无法发现硬盘
  • ¥15 MATLAB与UR10e实体机械臂建立通讯
  • ¥15 c++题需要快一点不用opencv