10条PHP高级技巧[修正版]

2019-04-09 01:06:22于海丽

根据本文的内容, 我们相应作者的意思应该是 “braces,” 而不是brackets. “Curly brackets” 可能有大括号的意思, 但是”brackets” 通常表示 “方括号”的意思。这个技巧应该被无条件的忽略,因为,没有大括号,可读性和可维护性被破坏了。
举一个简单的例子:

<?php
if (date('d M') == '21 May')
$birthdays = array('Al Franken',
'Chris Shiflett',
'Chris Wallace',
'Lawrence Tureaud');
?>

If you're good enough, smart enough, secure enough, notorious enough, or pitied enough, 你可能会想在5月21号参加社交聚会:

<?php
if (date('d M') == '21 May')
$birthdays = array('Al Franken',
'Chris Shiflett',
'Chris Wallace',
'Lawrence Tureaud');
party(TRUE);
?>

没有大括号,这个简单的条件导致你每天参加社交聚会 。也许你有毅力,因此这个错误是一个受欢迎的。希望那个愚蠢的例子并不分散这一的观点,那就是过度狂欢是一种出人意料的副作用。
为了提倡丢掉大括号,先前的文章使用类似下面的简短的语句作为例子:

<?php
if ($gollum == 'halfling') $height --;
else $height ++;
?>

因为每个条件被放在单独的一行, 这种错误似乎会较少发生, 但是这将导致另一个问题:代码的不一致和需要更多的时间来阅读和理解。一致性是这样一个重要的特性,以致开发人员经常遵守一个编码标准,即使他们不喜欢编码标准本身。
我们提倡总是使用大括号:

<?php
if (date('d M') == '21 May') {
$birthdays = array('Al Franken',
'Chris Shiflett',
'Chris Wallace',
'Lawrence Tureaud');
party(TRUE);
}
?>

你天天聚会是没关系的,但要保证这是经过思考的,还有,请一定要邀请我们!
5. 尽量用str_replace() 而不是 ereg_replace() 和 preg_replace()
我们讨厌听到的否认的话,但是(原文)这个用于演示误用的小技巧导致了它试图避免的同样的滥用问题。(
We hate to sound disparaging, but this tip demonstrates the sort of misunderstanding that leads to the same misuse it's trying to prevent.)
很明显字符串函数比正则表达式函数在字符匹配方面更快速高效,但是作者糟糕地试图从失败中得出一个推论:
(FIX ME: It's an obvious truth that string functions are faster at string matching than regular expression functions, but the author's attempt to draw a corollary from this fails miserably:)
If you're using regular expressions, then ereg_replace() and preg_replace() will be much faster than str_replace().
Because str_replace() does not support pattern matching, this statement makes no sense. The choice between string functions and regular expression functions comes down to which is fit for purpose, not which is faster. If you need to match a pattern, use a regular expression function. If you need to match a string, use a string function.
相关文章 大家在看