PHP简写概述

发布于 2024-10-10 06:31:19 字数 242 浏览 9 评论 0原文

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

谷歌搜索几乎专门显示了 if/else 语句的简写,但我知道肯定不止这些。

通过速记,我正在谈论这样的事情:

($var) ? true : false;

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.

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

By shorthand, I am talking about stuff like:

($var) ? true : false;

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

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

发布评论

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

评论(10

南烟 2024-10-17 06:31:19

以下是 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];

Here are some of the shorthand operators used in 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];
戏蝶舞 2024-10-17 06:31:19

PHP 5.3 引入:

$foo = $bar ?: $baz;

如果 $bar 计算结果为 true,则将 $bar 的值分配给 $foo(否则$baz)。

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

除此之外,没有太多其他的事情了。您可能需要阅读文档< /em>

PHP 5.3 introduced:

$foo = $bar ?: $baz;

which assigns the value of $bar to $foo if $bar evaluates to true (else $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.

蔚蓝源自深海 2024-10-17 06:31:19

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

例如,考虑以下函数,该函数接受数组作为参数,并且需要知道键 'color''shape' 和 'size'已设置。但也许用户并不总是知道这些是什么,因此您想为他们提供一些默认值。

第一次尝试时,人们可能会尝试这样的操作:

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']}";
}

但是,使用数组并集运算符可能是一个很好的“速记”,可以使此操作更清晰。考虑以下函数。它的行为与第一个完全相同,但更清晰:

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']}";
}    

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

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

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

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.

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:

array_walk($array, function($v) { return $v * 2; });
奶气 2024-10-17 06:31:19

没有人提到??

// 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';
}

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';
}
念﹏祤嫣 2024-10-17 06:31:19

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

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

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

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

This is called the ternary operator, 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.

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

茶色山野 2024-10-17 06:31:19

PHP7 中的另一个新功能是宇宙飞船操作符。主要用于诸如 usort() 之类的回调。

之前:

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

之后:

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

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

Also new in PHP7 is the spaceship operator. Mostly useful in callbacks for things like 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.

喜爱皱眉﹌ 2024-10-17 06:31:19

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

因此,有时,当您学习一种新的逻辑或新的运算符(例如本例)时,有帮助的是考虑英语(或您的母语是什么)来适应它。用一句话描述一下。让我们讨论一下您的示例:

($var) ? true : false;

这应该读作如下:

$var 是否为 true?如果 $var 为 true,则返回值 true。如果 $var 为 false,则返回值 false

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

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

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

echo $output;

所以这一行如下:

汽车的颜色与字符串“blue”相同?
如果是,返回字符串“Whee this car is blue!”,否则返回字符串“This car isn't blue at all.”

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

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.

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.

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:

$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."

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.

不语却知心 2024-10-17 06:31:19

从 5.4 开始,你也有了数组文字,所以你不再需要写:

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

你可以写:

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

差别不大,但相当不错。

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

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

You can just write:

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

Not a huge difference but pretty nice.

酒废 2024-10-17 06:31:19
<?php
class Bob {

    public function isDebug(){
        return true;
    }

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


$bob = new Bob(); 

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

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

<?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

天气好吗我好吗 2024-10-17 06:31:19

PHP 7.4 通过 fn 关键字引入了箭头函数。

$x = 5;
$my_function = fn($y) => $x * 5;
echo $my_function(4); // echos "20"

另请参阅这篇 W3Schools 文章,了解更多说明。

PHP 7.4 introduced the arrow functions via the fn keyword.

$x = 5;
$my_function = fn($y) => $x * 5;
echo $my_function(4); // echos "20"

Also see this W3Schools article for a little more explanation.

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