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 三极管1000倍放大电路
  • ¥15 vscode报错如何解决
  • ¥15 前端vue CryptoJS Aes CBC加密后端java解密
  • ¥15 python随机森林对两个excel表格读取,shap报错
  • ¥15 基于STM32心率血氧监测(OLED显示)相关代码运行成功后烧录成功OLED显示屏不显示的原因是什么
  • ¥100 X轴为分离变量(因子变量),如何控制X轴每个分类变量的长度。
  • ¥30 求给定范围的全体素数p的(p-2)/p的连乘积值
  • ¥15 VFP如何使用阿里TTS实现文字转语音?
  • ¥100 需要跳转番茄畅听app的adb命令
  • ¥50 寻找一位有逆向游戏盾sdk 应用程序经验的技术