【问题标题】:How can I use a "variable" in an if/or statement in PHP to generate a statement conditionally?如何在 PHP 的 if/or 语句中使用“变量”有条件地生成语句?
【发布时间】:2011-12-08 12:57:48
【问题描述】:

我对 PHP 的经验为零。我运行一个 wordpress 站点,并试图对代码进行一个简单的修改。这就是我所拥有的:

    <?php
    if(<?php the_author() ?> == "Joe Man")
    {
    <?php the_author() ?>
    }
    ?>

我相信所有变量都以 $ 开头,所以我上面的 if 语句不是变量。我该怎么办?我也尝试创建一个变量,如下所示:

    <?php
    $author = <?php the_author() ?>
    if($author == "Joe Man")
    {
    <?php the_author() ?>
    }
    ?>

以上都不起作用。所以我的问题是我怎样才能得到那个 if 语句来评估?我需要的是如果 the_author 是“Joe Man”,则字符串“Joe Man”会显示在我的页面上。

这是我得到的错误:

解析错误:语法错误,意外'

谢谢!

【问题讨论】:

  • PHP 中的 PHP ... 新的开始!
  • 大声笑不知道我已经走了那么远

标签: php variables if-statement parse-error


【解决方案1】:

您不能嵌套&lt;?php ?&gt; 标签。正确的代码是:

<?php
    $author = get_the_author();
    if ($author == "Joe Man") {
        echo $author;
    }
?>

实际上,可以完全跳过该变量,将代码缩短为:

<?php
    if (get_the_author() == "Joe Man") {
        the_author();
    }
?>

注意 echo 以打印出作者。

【讨论】:

  • 你的意思是在上面的例子中回显 $author 而不是 the_author()。如果你不这样做,它会让变量赋值变得毫无意义。
  • 因此我声明该变量可以完全跳过。虽然你是对的。我会解决的。
  • 我现在明白了。但奇怪的事情正在发生。只需拥有这段代码:the_author();无论在哪里,都会在我的页面上显示名称。对于缩短版,如果 the_author 是 Joe Man,Joe Man 会出现 3 次:一次用于 echo 命令,两次用于代码中 the_author 的两个实例。
  • 那么这意味着函数the_author()不返回作者姓名,它打印它。在这种情况下,您需要调用 get_the_author(),它会返回它。
  • 爱你们。应该有一个程序员感谢日,认真的。像魅力一样工作!
【解决方案2】:

看起来您正在使用 wordpress,因此除了您的 PHP-in-PHP 错误之外,您的代码无论如何都无法工作,因为两个 the_author() 调用都会简单地输出数据,而不是返回数据进行比较。你想要:

$author = get_the_author();
if ($author == "Joe Man") {
   echo $author;
}

相反。作为一般规则,Wordpress 中任何输出的函数都有一个get_...() 变体,它返回而不是输出。

【讨论】:

    【解决方案3】:

    如果作者是“乔曼”,输出作者:

    <?php
      $author = the_author();
      if($author == "Joe Man") {
        echo $author;
      }
    ?>
    

    【讨论】:

    • 你说的有效,但出于某种原因,运行这段代码:the_author();无论在哪里,都使名称显示在页面上。有没有办法抑制这种情况?
    猜你喜欢
    • 1970-01-01
    • 2016-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多