我已经用PHP编程很多年了,但是我从来没有学会过如何使用速记。我经常在代码中遇到它,并且很难读懂它,所以我想学习这门语言的不同速记,这样我就可以阅读它,并开始使用它来节省时间/行数,但我似乎找不到所有速记的全面概述。
谷歌搜索几乎只显示if/else语句的简写,但我知道肯定不止这些。
简而言之,我是在谈论类似这样的东西:
($var) ? true : false;发布于 2010-12-31 08:52:52
下面是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];发布于 2010-12-31 08:37:38
PHP 5.3引入:
$foo = $bar ?: $baz;如果$bar的计算结果为true (否则为$baz),则将$bar的值赋给$foo。
您还可以嵌套三元运算符(正确使用括号)。
除此之外,没有太多关于它的东西。您可能想要阅读。
发布于 2010-12-31 08:56:14
我在PHP中最喜欢的“技巧”之一就是在处理一些情况时使用array 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']}";
}但是,使用数组并集运算符可以很好地“简化”这一过程。考虑下面的函数。它具有与第一个完全相同的行为,但更加清晰:
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']}";
} 另一个有趣的事情是anonymous functions (和闭包,在PHP5.3中引入)。例如,要将数组中的每个元素乘以2,您只需执行以下操作:
array_walk($array, function($v) { return $v * 2; });https://stackoverflow.com/questions/4567292
复制相似问题