简体   繁体   English

由于“ echo”语句不返回任何值,因此“三元运算符”(即“条件运算符”)如何与“ echo”语句一起使用?

[英]How does the 'Ternary Operator' i.e. the 'conditional operator' work with the 'echo' statement since the 'echo' statement doesn't return any value?

I'm using PHP 7.3.6 on my laptop that runs on Windows 10 Home Single Language 64-bit operating system . 我在运行Windows 10家庭单一语言64位操作系统的笔记本电脑上使用PHP 7.3.6

I've installed the latest version of XAMPP installer on my laptop which has installed the Apache/2.4.39 (Win64) and PHP 7.3.6 我已经在笔记本电脑上安装了最新版本的XAMPP安装程序,该安装程序已经安装了Apache / 2.4.39(Win64)PHP 7.3.6。

Today, I come across following code example from the PHP Manual : 今天,我遇到了PHP手册中的以下代码示例:

<?php
  echo $some_var ? 'true': 'false'; // changing the statement around
?>

As per my knowledge and according to the following text from PHP Manual : 据我所知并根据PHP手册中的以下文本:

The expression (expr1) ? 表达式(expr1)? (expr2) : (expr3) evaluates to expr2 if expr1 evaluates to TRUE , and expr3 if expr1 evaluates to FALSE . (expr2):(expr3)如果expr1的值为TRUE则计算为expr2,如果expr1的值为FALSE则为expr3。

It's also a well-known fact that echo statement in PHP doesn't return any value. 众所周知,PHP中的echo语句不返回任何值。

So, in the code example mentioned above also echo statement must not be returning any value. 因此,在上述代码示例中, echo语句也必须不返回任何值。

So, my question is as the echo statement never returns any value how does the ternary operator comes to know that expr1(ie the statement echo $some_var) has been evaluated to true or false and accordingly prints the output as true or false ? 所以,我的问题是,由于echo语句从不返回任何值,三元运算符如何知道expr1(ie the statement echo $some_var)已被评估为true或false,并因此将输出打印为truefalse

you're reading the logic incorrectly. 您错误地阅读了逻辑。 Which is why I like brackets for my ternary statements. 这就是为什么我喜欢三元陈述的括号。 Your ternary is the same as: 您的三元与:

if ($some_var) {
    echo 'true';
} else {
    echo 'false';
}

the echo isn't being used in the conditional. 条件中未使用回声。 If we change the ternary to this, things are clearer: 如果我们将三元数更改为此,则情况会更清楚:

echo ($some_var ? 'true' : 'false');

this can be seen as echo (if ($some_var) {true} else {false}) (from a logic point of view at least) 这可以看作是echo (if ($some_var) {true} else {false}) (至少从逻辑观点来看)

So it's not the echo that's being tested, it's the bit before the ? 因此,测试的不是回声,而是? - that's the if statement conditional, not the echo -这是有条件的if语句,而不是echo

Echo is kind of a strange player in the PHP game. Echo在PHP游戏中有点奇怪。 When it is executed, it is actually wrapping your statement in parenthesis to be more like a function. 当它执行时,实际上是将您的语句括在括号中,使其更像一个函数。

So 所以

<?php

$something = true;

// this
echo $something ? 'is true' : 'is false';

// becomes 
echo($something ? 'is true' : 'is false');

where the ternary expression evaluates to 'is true' and that is "echoed". 三元表达式的计算结果为“ true”,即为“ echoed”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM