【问题标题】:if statment within an echo using ternary operators使用三元运算符的回显中的 if 语句
【发布时间】:2016-03-05 19:50:48
【问题描述】:

我有如下回显语句:

echo '<li><a href="'. esc_url(add_query_arg( 'booking-id', $the_query->post->ID, site_url( '/pay-deposit/' ) )) .'">Pay deposit</a></li>';

当参数 = 1 时,我想将“禁用”类添加到链接中

这是我正在尝试使用三元运算符的方法

    $is_deposit_paid = get_post_meta( $the_query->post->ID, 'deposit_paid', true );
    echo '<li><a '.( $is_deposit_paid = 1) ? "disabled" .' href="'. esc_url(add_query_arg( 'booking-id', $the_query->post->ID, site_url( '/pay-deposit/' ) )) .'">Pay deposit</a></li>';

但是这会产生语法错误。如何正确写出来?

【问题讨论】:

  • $is_deposit_paid = 1 永远为真,这不是比较。

标签: php if-statement echo ternary-operator


【解决方案1】:

需要解决三个问题:

    1234563李>
  • 在构建字符串之前,应将整个三元表达式放在括号中(而不是条件)。

  • 你需要比较,而不是分配(== 而不是=

这样就可以了:

$is_deposit_paid = get_post_meta( $the_query->post->ID, 'deposit_paid', true );
echo '<li><a '.( $is_deposit_paid == 1  ? "disabled" : "") . 
    ' href="'. esc_url(add_query_arg( 'booking-id', $the_query->post->ID, 
        site_url( '/pay-deposit/' ) )) . 
    '">Pay deposit</a></li>';

【讨论】:

  • 不。这不是比较而是赋值(= 而不是 ==)。因此,它永远是正确的。
【解决方案2】:

只需在函数调用后立即使用一个变量,类被“禁用”或什么都没有(“”):

$is_deposit_paid = get_post_meta( $the_query->post->ID, 'deposit_paid', true );
$class = ($is_deposit_paid)?"disabled":"";
echo "<li><a $class href='". esc_url(add_query_arg( 'booking-id', $the_query->post->ID, site_url( '/pay-deposit/' ) )) ."'>Pay deposit</a></li>";

如果你只需要类,你甚至可以立即检查函数调用:

$class = (get_post_meta( $the_query->post->ID, 'deposit_paid', true ))?"disabled":"";

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-20
    • 2018-12-08
    • 1970-01-01
    • 2012-08-28
    • 2011-05-10
    • 2018-12-26
    • 1970-01-01
    • 2017-11-19
    相关资源
    最近更新 更多