PHP 速记概述

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4567292/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 13:29:36  来源:igfitidea点击:

Overview of PHP shorthand

phpshorthand

提问by James Simpson

I've been programming in PHP for years now, but I've never learned how to use any shorthand. I come across it from time to time in code and have a hard time reading it, so I'd like to learn the different shorthand that exists for the language so that I can read it and start saving time/lines by using it, but I can't seem to find a comprehensive overview of all of the shorthand.

我已经用 PHP 编程多年了,但我从来没有学会如何使用任何速记。我不时在代码中遇到它并且很难阅读它,所以我想学习该语言存在的不同速记,以便我可以阅读它并开始通过使用它来节省时间/行,但是我似乎无法找到所有速记的全面概述。

A Google search pretty much exclusively shows the shorthand for if/else statements, but I know there must be more than just that.

Google 搜索几乎只显示 if/else 语句的简写,但我知道肯定不止这些。

By shorthand, I am talking about stuff like:

简而言之,我说的是这样的东西:

($var) ? true : false;

回答by Click Upvote

Here are some of the shorthand operators used in PHP.

以下是 PHP 中使用的一些速记运算符。

//If $y > 10, $x will say 'foo', else it'll say 'bar'
$x = ($y > 10) ? 'foo' : 'bar';

//Short way of saying <? print $foo;?>, useful in HTML templates
<?=$foo?>

//Shorthand way of doing the for loop, useful in html templates
for ($x=1; $x < 100; $x++):
   //Do something
end for;

//Shorthand way of the foreach loop
foreach ($array as $key=>$value):
   //Do something;
endforeach;

//Another way of If/else:
if ($x > 10):
    doX();
    doY();
    doZ();
else:
    doA();
    doB();
endif;

//You can also do an if statement without any brackets or colons if you only need to
//execute one statement after your if:

if ($x = 100)
   doX();
$x = 1000;

// PHP 5.4 introduced an array shorthand

$a = [1, 2, 3, 4];
$b = ['one' => 1, 'two' => 2, 'three' => 3, 'four' => 4];

回答by Felix Kling

PHP 5.3 introduced:

PHP 5.3 介绍:

$foo = $bar ?: $baz;

which assigns the value of $barto $fooif $barevaluates to true(else $baz).

如果计算结果为(else ) $bar$foo则分配to的值。$bartrue$baz

You can also nest the ternary operator (with proper use of parenthesis).

您还可以嵌套三元运算符(正确使用括号)。

Other than that, there is not much else about it. You might want to read the documentation.

除此之外,没有太多关于它的。您可能需要阅读文档

回答by mfonda

One of my favorite "tricks" in PHP is to use the array unionoperator when dealing with situations such as functions that take an array of arguments, falling back on default values.

我在 PHP 中最喜欢的“技巧”之一是在处理诸如采用参数数组的函数、回退到默认值等情况时使用数组联合运算符。

For example, consider the following function that accepts an array as an argument, and needs to know that the keys 'color', 'shape', and 'size' are set. But maybe the user doesn't always know what these will be, so you want to provide them with some defaults.

例如,考虑下面的函数接受一个数组作为参数,并且需要知道的是,键'color''shape'和“ size”是集。但也许用户并不总是知道这些是什么,所以你想为他们提供一些默认值。

On a first attempt, one might try something like this:

在第一次尝试时,人们可能会尝试这样的事情:

function get_thing(array $thing)
{
    if (!isset($thing['color'])) {
        $thing['color'] = 'red';
    }
    if (!isset($thing['shape'])) {
        $thing['shape'] = 'circle';
    }
    if (!isset($thing['size'])) {
        $thing['size'] = 'big';
    }
    echo "Here you go, one {$thing['size']} {$thing['color']} {$thing['shape']}";
}

However, using the array union operator can be a good "shorthand" to make this cleaner. Consider the following function. It has the exact same behavior as the first, but is more clear:

然而,使用数组联合运算符可以是一个很好的“速记”,可以使这个更简洁。考虑以下函数。它的行为与第一个完全相同,但更清晰:

function get_thing_2(array $thing)
{
    $defaults = array(
        'color' => 'red',
        'shape' => 'circle',
        'size'  => 'big',
    );
    $thing += $defaults;
    echo "Here you go, one {$thing['size']} {$thing['color']} {$thing['shape']}";
}    

Another fun thing is anonymous functions, (and closures, introduced in PHP 5.3). For example, to multiple every element of an array by two, you could just do the following:

另一个有趣的事情是匿名函数(和闭包,在 PHP 5.3 中引入)。例如,要将数组的每个元素乘以二,您只需执行以下操作:

array_walk($array, function($v) { return $v * 2; });

回答by Robert Pounder

Nobody mentioned ??!

没人提??

// Example usage for: Null Coalesce Operator
$action = $_POST['action'] ?? 'default';

// The above is identical to this if/else statement
if (isset($_POST['action'])) {
    $action = $_POST['action'];
} else {
    $action = 'default';
}

回答by Jacob Relkin

This is called the ternaryoperator, a boolean operator that has three operands:

这称为三元运算符,一种具有三个操作数的布尔运算符:

The first is the boolean expression to evaluate.

第一个是要计算的布尔表达式。

The second is the expression to execute if the boolean expression evaluates to TRUE.

第二个是当布尔表达式计算为 TRUE 时要执行的表达式。

The third is the expression to execute if the boolean expression evaluates to FALSE.

第三个是布尔表达式计算结果为 FALSE 时要执行的表达式。

回答by Okonomiyaki3000

Also new in PHP7 is the spaceship operator. Mostly useful in callbacks for things like usort().

PHP7 中的另一个新功能是飞船操作员。主要用于诸如usort().

Before:

前:

usort($list, function ($a, $b) {
    if ($a == $b) return 0;
    return $a < $b;
});

After:

后:

usort($list, function ($a, $b) { return $a <=> $b; });

Basically, it returns a negative integer, 0, or a positive integer based on the comparison of the left side with the right side.

基本上,它根据左侧与右侧的比较返回一个负整数、0 或正整数。

回答by Mattygabe

So, Jacob Relkin is absolutely right in that the "shorthand" that you mention is indeed called the "ternary" operator, and as Sam Dufel adds, it is very prevalent in other languages. Depending on how the language implements it, it may even be quicker for the server to interpret the logic, as well as let you read it more quickly.

因此,Jacob Relkin 是绝对正确的,因为您提到的“速记”确实称为“三元”运算符,并且正如 Sam Dufel 补充的那样,它在其他语言中非常普遍。根据语言的实现方式,服务器甚至可以更快地解释逻辑,并让您更快地阅读它。

So sometimes what helps when you're learning a new piece of logic or new operators such as this one is to think of the English (or whatever your native language is) to fit around it. Describe it in a sentence. Let's talk through your example:

因此,有时在您学习新的逻辑或新的运算符(例如这个)时,考虑英语(或任何您的母语)以适应它是有帮助的。用一句话描述一下。让我们来谈谈你的例子:

($var) ? true : false;

What this should read as is this:

这应该是这样的:

Is $var true?If $var is, return the value true. If $var is false, return the value false.

$var 是真的吗?如果 $var 是,则返回值 true。如果 $var 为 false,则返回值 false

The question mark helps remind you that you're asking a question that determines the output.

问号有助于提醒您您正在提出一个决定输出的问题。

A more common use-case for the ternary operator is when you are checking something that isn't necessarily a boolean, but you can use boolean logic to describe it. Take for example the object Car, that has a property called color, which is a string-like variable (in PHP). You can't ask if a string is true or false because that makes no sense, but you can ask different questions about it:

三元运算符的一个更常见的用例是当您检查不一定是布尔值但您可以使用布尔逻辑来描述它时。以 object 为例Car,它有一个名为 的属性color,它是一个类似字符串的变量(在 PHP 中)。你不能问一个字符串是真还是假,因为那没有意义,但你可以提出不同的问题:

$output = $car->color == "blue" ? "Wheee this car is blue!" : "This car isn't blue at all.";

echo $output;

So this line reads as follows:

所以这行内容如下:

Is the color of car the same as the string "blue"?
If it is, return the string "Whee this car is blue!", otherwise return the string "This car isn't blue at all."

汽车的颜色是否与字符串“blue”相同?
如果是,则返回字符串“哇,这辆车是蓝色的!” ,否则返回字符串“这辆车根本不是蓝色的”。

Whatever the ternary operator returns is being used in the right-hand side of an assignment statement with $output, and that string is then printed.

无论三元运算符返回什么,都在带有 $output 的赋值语句的右侧使用,然后打印该字符串。

回答by Natdrip

<?php
class Bob {

    public function isDebug(){
        return true;
    }

    public function debug(){
        echo 'yes dice!!!';
    }
}


$bob = new Bob(); 

($bob->isDebug()) && $bob->debug(); 

Here is another version of shorthand. Hope this helps someone

这是速记的另一个版本。希望这有助于某人

回答by Okonomiyaki3000

Since 5.4 you also have array literals so you no longer need to write:

从 5.4 开始,您还有数组文字,因此您不再需要编写:

$myArray = array('some', 'list', 'of', 'stuff');

You can just write:

你可以只写:

$myArray = ['some', 'list', 'of', 'stuff'];

Not a huge difference but pretty nice.

差别不大,但相当不错。