【问题标题】:How to use if and endif statment in ternary operator? [closed]如何在三元运算符中使用 if 和 endif 语句? [关闭]
【发布时间】:2021-02-13 20:56:11
【问题描述】:

我正在尝试编写 php 函数,但我卡在这里如何在三元运算符中编写 if 和 endif 语句?我将?: 用于 if 和 endif 但在我的情况下它不起作用。这是我的 if 和 endif 语句:

<?php if (class_exists('my_class')) : ?>
<?php endif; ?>

这是我试图实现这一目标的方法,但我一直面临解析错误:

$mycode = ''. (class_exists('my_class')) ? : '') .'';
$mycode .= ':';

非常感谢任何帮助。
已编辑
这是我完整的 html 和 php:

<form name="myform" method="GET" action="<?php echo esc_url(home_url('/')); ?>">
<?php if (class_exists('my_class')) : ?>
<input type="hidden" value="product" name="post_type">
<?php endif; ?>
<input type="text"  name="s" class="searchbox" maxlength="128" value="<?php echo get_search_query(); ?>">

这是我如何转换它的:

<?php
$mycode = '<div class="main_form"><form name="myform" method="GET" action="'.esc_url(home_url('/')).'">';
$mycode .= ''. (class_exists('my_class')) ? : '') .'';
$mycode .='<input type="hidden" value="product" name="post_type">';
$mycode .= ':';
?>

【问题讨论】:

  • 不清楚你到底想要达到什么目的。 ?: 不是 if/endif 的同义词,并且三元运算符不能跨 PHP 开始/结束标记进行分解。您可能会发现 Shorthand comparisons in PHP 是一本有用的读物​​。同时,请说明您想要的结果是什么。
  • edit您的问题包含您收到的确切错误消息。还要仔细阅读它,并试着想一想它可能会告诉你什么。
  • 三元运算符顾名思义包括三个部分——条件、结果为真和结果为假。我看不到您的代码在任何地方都需要这 3 个部分,只有两个部分(如果满足条件,则回显一个额外的 HTML 输入元素)。您认为需要使用三元运算符或想要使用三元运算符有什么原因吗?

标签: php conditional-operator


【解决方案1】:

我认为您正在寻找类似的东西 $mycode = class_exists('my_class') ? '东西' : '别的东西';

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-04
    • 1970-01-01
    • 2021-09-15
    • 2013-07-01
    • 1970-01-01
    • 2013-03-19
    • 2010-12-03
    • 1970-01-01
    相关资源
    最近更新 更多