PHP简写概述

Jam*_*son 34 php shorthand

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

谷歌搜索几乎只显示if/else语句的简写,但我知道必须有更多.

简而言之,我说的是:

($var) ? true : false;
Run Code Online (Sandbox Code Playgroud)

Cli*_*ote 68

以下是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];
Run Code Online (Sandbox Code Playgroud)

  • 那*替代语法*"简写"怎么样?如果有的话,那就是手写的.如果没有气馁并且依赖于短开标签,我会继续使用`<?=`. (7认同)
  • @deceze - 在php => 5.4`<?=`不依赖于短开标签, (2认同)

Fel*_*ing 22

PHP 5.3介绍:

$foo = $bar ?: $baz;
Run Code Online (Sandbox Code Playgroud)

其分配的值$bar,以$foo如果$bar计算结果为true(其他$baz).

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

除此之外,没有其他相关内容.您可能想阅读文档.


mfo*_*nda 16

PHP中我最喜欢的"技巧"之一是在处理诸如带有参数数组的函数之类的情况时使用数组union运算符,然后回退到默认值.

例如,考虑下面的函数接受一个数组作为参数,并且需要知道密钥'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']}";
}
Run Code Online (Sandbox Code Playgroud)

但是,使用数组联合运算符可以很好地"简化"以使其更清洁.考虑以下功能.它具有与第一个完全相同的行为,但更清楚:

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']}";
}    
Run Code Online (Sandbox Code Playgroud)

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

array_walk($array, function($v) { return $v * 2; });
Run Code Online (Sandbox Code Playgroud)


Rob*_*der 5

没人提到??

// 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';
}
Run Code Online (Sandbox Code Playgroud)

  • 在问题提出大约 5 年后,在 PHP 7 中引入。确实是一个有用的运算符。有关“??”和“?:”的更多信息,请参见:/sf/ask/2419993131/ (3认同)