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条)

报告相同问题?

悬赏问题

  • ¥50 vue组件中无法正确接收并处理axios请求
  • ¥15 隐藏系统界面pdf的打印、下载按钮
  • ¥15 MATLAB联合adams仿真卡死如何解决(代码模型无问题)
  • ¥15 基于pso参数优化的LightGBM分类模型
  • ¥15 安装Paddleocr时报错无法解决
  • ¥15 python中transformers可以正常下载,但是没有办法使用pipeline
  • ¥50 分布式追踪trace异常问题
  • ¥15 人在外地出差,速帮一点点
  • ¥15 如何使用canvas在图片上进行如下的标注,以下代码不起作用,如何修改
  • ¥50 vue router 动态路由问题