PHP 运算符“?”是什么? 和“:” 他们会做什么?

发布于 2024-07-26 06:31:46 字数 149 浏览 8 评论 0原文

PHP 中的 ?: 运算符是什么?

例如:

(($request_type == 'SSL') ? HTTPS_SERVER : HTTP_SERVER)

What are the ? and : operators in PHP?

For example:

(($request_type == 'SSL') ? HTTPS_SERVER : HTTP_SERVER)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

心房敞 2024-08-02 06:31:46

这是条件运算符

$x ? $y : $z

表示“如果 $x 为 true,则使用 $y;否则使用 $z”。

它也有一个简短的形式。

$x ?: $z

表示“如果 $x 为 true,则使用 $x;否则使用 $z”。

人们会告诉你 ?: 是“三元运算符”。 这是错误的。 ?:一个三元运算符,这意味着它有三个操作数。 人们最终认为它的名字是“三元运算符”,因为它通常是给定语言拥有的唯一三元运算符。

This is the conditional operator.

$x ? $y : $z

means "if $x is true, then use $y; otherwise use $z".

It also has a short form.

$x ?: $z

means "if $x is true, then use $x; otherwise use $z".

People will tell you that ?: is "the ternary operator". This is wrong. ?: is a ternary operator, which means that it has three operands. People wind up thinking its name is "the ternary operator" because it's often the only ternary operator a given language has.

朕就是辣么酷 2024-08-02 06:31:46

我将写一些关于三元的内容,它们是什么,如何使用它们,何时以及为什么使用它们以及何时不使用它们。

什么是三元运算符?

三元? :ifelse 的简写。 基本上就是这样。 请参阅此页面中的“三元运算符”了解更多官方信息解释。

从 PHP 5.3 开始

从 PHP 5.3 开始,可以省略三元运算符的中间部分。 如果 expr1 计算结果为 TRUE,则表达式 expr1 ?: expr3 返回 expr1,否则返回 expr3。

从 PHP 7.0 开始

PHP 7 有新的空合并运算符。 这与三元相同,但也称为“isset 三元”。 这还允许使用一组链式三元组,从而无需 isset() 检查。

那么您必须在三元语句的开头执行 isset():

$result = isset($nonExistentVariable) ? $nonExistentVariable : ‘default’;

在 PHP 7 中,您现在可以这样做:

$result = $nonExistentVariable ?? ‘default’;

在 PHP 5 中,如果您想使用带有可能不存在的变量的三元, 但是,运算符不适用于空字符串,因此请记住这一点。 这样做的好处是,您还可以链接运算符以对多个变量进行多次检查,根据链中的每个变量是否存在提供某种备份:

$user = $userImpersonatingAnotherUser ?? $loggedInUser ?? “Guest”;

在 PHP 中,对于用户可以登录的系统,它不是管理员能够冒充其他用户进行测试的情况并不常见。 在上面的示例中,如果用户没有模拟其他用户,并且登录用户不存在,则该用户将成为访客用户。 如果您还不明白,请继续阅读以了解三元数是什么以及如何使用它们,然后回到这一点来了解新的 PHP

如何使用三元数?

以下是如何使用三元数正常的 if 语句看起来:

if (isset($_POST['hello']))
{
    $var = 'exists';
}
else
{
    $var = 'error';
}

让我们将其缩短为三元。

$var = isset($_POST['hello']) ? 'exists' : 'error';
                 ^            ^     ^    ^     |
                 |           then   |   else   |
                 |                  |          |
          if post isset         $var=this   $var=this

短得多,但可能更难阅读。 它们不仅用于设置像上例中的 $var 这样的变量,而且您还可以使用 echo 来执行此操作,并检查变量是否为 false:

$isWinner = false;

// Outputs 'you lose'
echo ($isWinner) ? 'You win!' : 'You lose';

// Same goes for return
return ($isWinner) ? 'You win!' : 'You lose';

人们为什么使用它们?

我认为三元体系很性感。 有些开发人员喜欢炫耀,但有时三元组只是在代码中看起来不错尤其是与 PHP 5.4 的最新 短回声

<?php 
    $array = array(0 => 'orange', 1 => 'multicoloured'); 
?>

<div>
    <?php foreach ($array as $key => $value) { ?>
        <span><?=($value==='multicoloured')?'nonsense':'pointless'?></span>
    <?php } ?>
</div>

<!-- Outputs:
    <span>
        pointless
    </span>
    <span>
        nonsense
    </span> 
-->

当您处于“视图/模板”中时,稍微偏离主题(如果您通过 MVC 范例),您希望其中的服务器端逻辑尽可能少。 因此,使用三元数和其他简写代码有时是最好的方法。 我所说的“其他简写代码”,我的意思是:

if ($isWinner) :
    // Show something cool
endif;

注意,我个人不喜欢这种 if / endif 废话的简写

三元运算符有多快?

人们喜欢微观优化。 他们就是这么做的。 因此,对于某些人来说,了解像三元这样的东西与普通的 if / else 语句相比要快多少非常重要。

阅读这篇文章,差异是约0.5毫秒。 好多啊!

哦等等,不,不是。 如果你连续重复地做成千上万次,这只是很多。 但你不会。 所以根本不用担心速度优化,这里绝对没有意义。

何时不使用三元组

你的代码应该是:

  • 易于阅读
  • 易于理解
  • 易于修改

显然,这取决于人们的智力和编码知识/在查看这些概念时对这些概念的一般理解水平你的代码。 像前面的示例一样的单个简单三元是可以的,但是,像下面这样的东西不是您应该做的:

echo ($colour === 'red') ? "Omg we're going to die" :
     ($colour === 'blue' ? "Ah sunshine and daisies" :
     ($colour === 'green' ? "Trees are green"
     : "The bloody colour is orange, isn't it? That was pointless."));

由于三个原因,这毫无意义:

  • 长得可笑的三元嵌入
  • 可以只使用switch 语句
  • 首先它是橙色的

结论

三元数确实很简单,没有什么值得大惊小怪的。 不要考虑任何速度改进,它真的不会产生任何影响。 当它们简单并且看起来不错时使用它们,并始终确保您的代码将来可以被其他人阅读。 如果这意味着没有三元数,那么就不要使用三元数。

I'm going to write a little bit on ternaries, what they are, how to use them, when and why to use them and when not to use them.

What is a ternary operator?

A ternary ? : is shorthand for if and else. That's basically it. See "Ternary Operators" half way down this page for more of an official explanation.

As of PHP 5.3:

Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.

As of PHP 7.0

PHP 7 has new Null Coalesce Operator. This is the same as a ternary but is also called an "isset ternary". This also allows a set of chained ternaries that remove the need for isset() checks.

In PHP 5, if you wanted to use a ternary with a potentially non-existent variable then you would have to perform an isset() at the beginning of the ternary statement:

$result = isset($nonExistentVariable) ? $nonExistentVariable : ‘default’;

In PHP 7, you can now do this instead:

$result = $nonExistentVariable ?? ‘default’;

The Null Coalesce Operator does not work with an empty string, however, so bear that in mind. The great thing about this is you can also chain the operators for multiple checks for multiple variables, providing a sort of backup depending on whether or not each variable in the chain exists:

$user = $userImpersonatingAnotherUser ?? $loggedInUser ?? “Guest”;

In PHP, with systems where a user can login, it is not uncommon for an administrator to be able to impersonate another user for testing purposes. With the above example, if the user is not impersonating another user, and also a logged in user does not exist, then the user will be a guest user instead. Read on more if you don't understand this yet to see what ternaries are and how they are used, and then come back to this bit to see how the new PHP

How are ternaries used?

Here's how a normal if statement looks:

if (isset($_POST['hello']))
{
    $var = 'exists';
}
else
{
    $var = 'error';
}

Let's shorten that down into a ternary.

$var = isset($_POST['hello']) ? 'exists' : 'error';
                 ^            ^     ^    ^     |
                 |           then   |   else   |
                 |                  |          |
          if post isset         $var=this   $var=this

Much shorter, but maybe harder to read. Not only are they used for setting variables like $var in the previous example, but you can also do this with echo, and to check if a variable is false or not:

$isWinner = false;

// Outputs 'you lose'
echo ($isWinner) ? 'You win!' : 'You lose';

// Same goes for return
return ($isWinner) ? 'You win!' : 'You lose';

Why do people use them?

I think ternaries are sexy. Some developers like to show off, but sometimes ternaries just look nice in your code, especially when combined with other features like PHP 5.4's latest short echos.

<?php 
    $array = array(0 => 'orange', 1 => 'multicoloured'); 
?>

<div>
    <?php foreach ($array as $key => $value) { ?>
        <span><?=($value==='multicoloured')?'nonsense':'pointless'?></span>
    <?php } ?>
</div>

<!-- Outputs:
    <span>
        pointless
    </span>
    <span>
        nonsense
    </span> 
-->

Going off-topic slightly, when you're in a 'view/template' (if you're seperating your concerns through the MVC paradigm), you want as little server-side logic in there as possible. So, using ternaries and other short-hand code is sometimes the best way forward. By "other short-hand code", I mean:

if ($isWinner) :
    // Show something cool
endif;

Note, I personally do not like this kind of shorthand if / endif nonsense

How fast is the ternary operator?

People LIKE micro-optimisations. They just do. So for some, it's important to know how much faster things like ternaries are when compared with normal if / else statements.

Reading this post, the differences are about 0.5ms. That's a lot!

Oh wait, no it's not. It's only a lot if you're doing thousands upon thousands of them in a row, repeatedly. Which you won't be. So don't worry about speed optimisation at all, it's absolutely pointless here.

When not to use ternaries

Your code should be:

  • Easy to read
  • Easy to understand
  • Easy to modify

Obviously this is subject to the persons intelligence and coding knowledge / general level of understanding on such concepts when coming to look at your code. A single simple ternary like the previous examples are okay, something like the following, however, is not what you should be doing:

echo ($colour === 'red') ? "Omg we're going to die" :
     ($colour === 'blue' ? "Ah sunshine and daisies" :
     ($colour === 'green' ? "Trees are green"
     : "The bloody colour is orange, isn't it? That was pointless."));

That was pointless for three reasons:

  • Ridiculously long ternary embedding
  • Could've just used a switch statement
  • It was orange in the first place

Conclusion

Ternaries really are simple and nothing to get too worked up about. Don't consider any speed improvements, it really won't make a difference. Use them when they are simple and look nice, and always make sure your code will be readable by others in the future. If that means no ternaries, then don't use ternaries.

时光与爱终年不遇 2024-08-02 06:31:46

它称为三元运算符。 如果第一个表达式的计算结果为 true,则使用 HTTPS_SERVER,否则选择 HTTP_SERVER

它基本上是一个简写的 if 语句,上面的代码也可以重写如下:

if ($request_type == 'SSL') {
   HTTPS_SERVER;
}
else {
   HTTP_SERVER;
}

It's called a ternary operator. If the first expression evaluates to true, HTTPS_SERVER is used, else HTTP_SERVER is chosen.

It's basically a shorthand if statement, and the above code could also be rewritten as follows:

if ($request_type == 'SSL') {
   HTTPS_SERVER;
}
else {
   HTTP_SERVER;
}
我早已燃尽 2024-08-02 06:31:46

这有时称为三元条件运算符。 三元意味着它有三个参数,如 x ? y:z。 基本上,它检查 x 是否为 true; 如果是,则用y代替此操作,否则用z

$hello = $something ? "Yes, it's true" : "No, it's false";

This is sometimes known as the ternary conditional operator. Ternary means that it has three arguments, as x ? y : z. Basically, it checks if x is true; if it is, then put y instead of this operation, otherwise z.

$hello = $something ? "Yes, it's true" : "No, it's false";
痴情 2024-08-02 06:31:46

条件运算符<代码>? : 是一个运算符,用于检查条件并根据条件的值选择一个值。 它以以下形式表示:

variable = condition ? expression1 : expression2;

它的工作原理如下...

  1. 首先,评估条件
  2. 如果条件为真,则对表达式1求值。 并且表达式1的值被分配给变量
  3. 如果条件为假,则计算表达式2。 并且将表达式2的值赋给该变量。

例如:

x = (a>b) ? 5 : 9

在此,对于x,首先评估条件(a>b)。 如果该条件成立,则x将变为值5(即x=5)。 但如果条件(a>b)变为假,则x将达到值9(即x=9)。

三元运算符

有时条件运算符? :也称为三元运算符。 之所以如此,是因为它涉及三个操作数。 例如:

x ? y : z

这里,x、y 和 z 是三个操作数。 如果条件 x 为真,则分配值 y,否则分配值 z。

Conditional operator ? : is an operator which is used to check a condition and select a value depending on the value of the condition. It is expressed in the following form:

variable = condition ? expression1 : expression2;

It works as follows...

  1. Firstly, condition is evaluated.
  2. If the condition is true, then expression1 is evalauated. And the value of expression1 is assigned to the variable.
  3. If the condition is false, then expression2 is evaluated. And the value of expression2 is assigned to the variable.

For example:

x = (a>b) ? 5 : 9

In this, for x, firstly the condition (a>b) is evaluated. If this condition becomes true, then x will become the value 5 (ie, x=5). But if the condition (a>b) becomes false, then x will attain the value 9 (ie, x=9).

Ternary Operator

Sometimes conditional operator ? : is also called a ternary operator. This is so because it involves three operands. For example:

x ? y : z

Here, x,y and z are the three operands. If condition x is true, then value y is assigned otherwise value z is assigned.

冷弦 2024-08-02 06:31:46

这是编写 if 句子的简短方法。 它还用于其他语言,如 Java、JavaScript 等。

你的代码

$protocol = $request_type == 'SSL' ? HTTPS_SERVER : HTTP_SERVER;

可以这样写:

if ($request_type == 'SSL')
    $protocol = HTTPS_SERVER;
else
    $protocol = HTTP_SERVER;

This is a short way of writing if sentences. It is also used in other languages like Java, JavaScript and others.

Your code,

$protocol = $request_type == 'SSL' ? HTTPS_SERVER : HTTP_SERVER;

can be written like this:

if ($request_type == 'SSL')
    $protocol = HTTPS_SERVER;
else
    $protocol = HTTP_SERVER;
你在我安 2024-08-02 06:31:46

这是一行 if 语句:

condition ? true : false

在您的情况下转换为普通的 if 语句,即:

if($request_type == 'SSL') HTTPS_SERVER;
else HTTP_SERVER;

That is a one line if statement:

condition ? true : false

Translated to an ordinary if statement in your case, that would be:

if($request_type == 'SSL') HTTPS_SERVER;
else HTTP_SERVER;
家住魔仙堡 2024-08-02 06:31:46

这基本上是编写 if-else 语句的一种奇特方式。 有人说它更容易阅读,有人说不是。

维基百科的三元运算符

That's basically a fancy way of writing an if-else statement. Some say it's easier to read, some say not.

Ternary operator at Wikipedia

白鸥掠海 2024-08-02 06:31:46

这就像 if 语句一样,一旦你习惯了它就会非常简单和容易。
(条件表达式) ? 如果为真则做什么:如果为假则做什么。

This works like an if statement it's very simple and easy once you get used to it.
(conditions_expressions) ? what_to_do_if_true : what_to_do_if_false.

厌味 2024-08-02 06:31:46

正如 John T 所说,它称为三元运算符,本质上是 if /else 语句的简写版本。 您的示例作为完整的 if / else 语句,将显示为;

if($request_type == 'SSL')
{
    HTTPS_SERVER;
}
else
{
    HTTP_SERVER;
}

As John T says, it is called a ternary operator and is essentially a shorthand version of an if /else statement. Your example, as a full if / else statement, would read;

if($request_type == 'SSL')
{
    HTTPS_SERVER;
}
else
{
    HTTP_SERVER;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文