一些PHP Coding Tips(php小技巧)[2011/04/02最后更新]
最后更新: 2011/04/02
1. 使用list来实现一次获取explode后的特定段值:
list( , $mid) = explode(';', $string);
2. 使用NULL === 来代替is_null:
is_null和 NULL === 完全是一样的效果, 但是却节省了一次函数调用.
3. 使用===尽量不用==:
PHP有俩组相等比较运算符===/!==和==/!=, ==/!=会有隐式类型转换,而===/!==会严格比较俩个操作时是否类型相同并且值相等.
我们应该尽量使用===而不是==, 除了因为转换规则比较难记以外, 还有一点就是如果使用===, 对于日后的维护或者阅读你代码的人也会很舒服:”在这个时刻, 这一行语句, 这个变量就是这个类型的!”.
4. 少用/不用 continue:
continue是回到循环的头部, 而循环结束本来就是回到循环的头部, 所以通过适当的构造, 我们完全可以避免使用这条语句, 使得效率得到改善.
5. 警惕switch/in_array等的松比较(loose comparision):
switch和in_array都是采用松比较, 所以在要比较的变量之间类型不一样的时候, 很容易出错:
复制代码 代码如下:
switch ($name) {
case "laruence":
...
break;
case "eve":
...
break;
}
对于上面的switch, 如果$name是数字0, 那么它会满足任何一条case. 同理在in_array中也是.
解决的办法就是, 在switch之前, 把变量类型转换成你所期望的类型.
复制代码 代码如下:
switch (strval($name)) {
case "laruence":
...
break;
case "eve":
...
break;
}
而, in_array提供了第三个可选的参数, 通过这个参数可以改变默认的比较方式.
6. switch不仅仅只用来判别变量:
比如, 对于如下的一段代码:
复制代码 代码如下:
if($a) {
} else if ($b) {
} else if ($c || $d) {
}
可以简单的改写为:
复制代码 代码如下:
switch (TRUE) {
case $a:
break;
case $b:
break;
case $c:
case $d:
break;
}
是不是看起来更清晰呢?
7. 变量先定义后使用:
使用一个未定义的变量, 比使用一个定义好的变量要慢8倍以上!
可以相像, PHP引擎会首先按照正常的逻辑来获取这个变量, 然而这个变量不存在, 所以PHP引擎需要抛出一个NOTICE, 并且进入一段使用未定义变量时应该走的逻辑, 然后返回一个新的变量.
另外, 阅读代码的角度讲, 当你使用一个未定义的变量时, 会让阅读你代码的人困惑:”这个变量在那里初始化的, 和之前的代码有关系么? 和include进来的文件有关系么?”
最后, 从规范编程的角度来讲, 你也需要这样做.
8. 不用第三变量交换俩个变量的值:
list($a, $b) = array($b, $a),
但其实还是有匿名临时变量的产生, 对于整数来说, 采用互逆的运算来做, 还是比较靠谱:
复制代码 代码如下:
$a = $a + $b;
$b = $a - $b;
$a = $a - $b;
不过, 还是用异或比较好, 因为+ – * /容易产生精度丢失或者溢出.
9. floor == 俩次非运算(此条由skiyo提供)
复制代码 代码如下:
echo ~~4.9;
echo floor(4.9);
用俩次非运算的速度基本上是floor的3倍, 不过有一点, 对于大数来说, 可能会发生溢出:
复制代码 代码如下:
echo ~~99999999999999.99; //276447231
echo floor(99999999999999.99); //99999999999999
10. do{}while(0)妙用(此条由Qianfeng提供)
我们知道do{}while(0)在c/c++中, 有很多妙用, 比如消除goto, 宏定义代码块.
所以, PHP中同理, 也可以用do{}while(0)来做一些巧妙的应用
复制代码 代码如下:
do{
if(true) {
break;
}
if(true) {
break;
}
} while(false);
//好过
if(true) {
} else if(true) {
} else {
}
11. 尽量少用@错误抑制符
如下代码:
复制代码 代码如下:
@func();
就相当于(参见深入理解PHP原理之错误抑制与内嵌HTML):
复制代码 代码如下:
$report = error_reporting(0);
func();
error_reporting($report);
另外错误抑制符号, 可能会造成一些问题, 参看(http://www.jb51.net/article/27022.htm);
最后,错误抑制符在发生错误调试的时候也可能会带来麻烦.
12. 尽量避免使用递归(此条来自lazyboy)
递归性能堪忧, 而大部分的递归都是尾递归, 都是可以消除的.
复制代码 代码如下:
function f($n) {
if ($n = 0) return 1;
return $n * f($n - 1);
}
//变为:
$result = 1;
for ($y = 1; $y $result *= $y;
}
13. 使用$_SERVER['REQUEST_TIME']代替time()
time()会引来一次函数调用, 而如果对时间的精确值要求不高, 可以使用$_SERVER['REQUEST_TIME']代替, 快很多.
14. 避免在for判断条件中做运算(此条来自留言的Anonymous)
如下的代码:
for($i=0; $i
会导致每次循环都调用strlen, 改为
for ($i=0, $j=strlen($str); $i}
15. 尽量避免使用正则(此条来自pangyontao)
正则耗时, 尽量避免, 而采用直接的字符串处理函数代替, 如:
复制代码 代码如下:
if (preg_match("!^foo_!i", "FoO_")) { }
// 替换为:
if (!strncasecmp("foo_", "FoO_", 4)) { }
if (preg_match("![a8f9]!", "sometext")) { }
// 替换为:
if (strpbrk("a8f9", "sometext")) { }
if (preg_match("!string!i", "text")) {}
// 替换为:
if (stripos("text", "string") !== false) {}
等等.
16. 用大括号括起在双引号和heredoc中的变量
如下的代码:
echo "$name[2]";
PHP不知道程序员的意图是$name . “[2]“还是$name[2],
所以建议, 都加上大括号:
复制代码 代码如下:
echo "{$name}[2]";
//或者
echo "${name}[2]";
17. 用FALSE表示错误, 用NULL表示不存在.
对于操作类的函数, 失败返回FALSE, 表示”操作失败了”, 而对于查询类的函数, 如果找不到想要的值, 则应该返回NULL, 表示”找不到”.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.
