返回正常中文阅读
想对这篇译文“指手画脚”吗?
大错
小错
不顺
建议 Ten PHP Best Practices Tips that will get you a job
The last couple of weeks have been quite the experience for me. I was part of a big layoff at my former company, which was interesting. I've never been in that position before, and it's hard not to take it personally. I started watching the job boards, and a nice-looking full-time PHP position caught my eye, so I sent out a resume and landed an interview. Before the face-to-face portion, I chatted with the owner and head programmer on a conference call, and they ended up sending me a technical assessment quiz. One particular question caught my eye on this quiz… it looked something like this:
Find the errors in the following code:
<?
function baz($y $z) {
$x = new Array();
$x[sales] = 60;
$x[profit] = 20:
foreach($x as $key = $value) {
echo $key+" "+$value+"<BR>"$$
}
}
?>
So, give it a shot. How many can you find?
If you got the missing comma in the parameter list, the "new Array()" error, the colon instead of a semi-colon, the '=' instead of '=>' in the foreach statement, and the erroneous use of '+' on the echo line, then congratulations, you found all the errors! You have the basic PHP technical skills to pay the bills.
That's not how I answered the question though. I noted the errors, obviously, but I went further than that. For instance, did you notice that there were no single quotes around the array indexes ($x[sales] and $x[profit])? That won't cause a fatal PHP error, but it is a coding error! Did you also notice the use of double-quoted strings instead of single-quoted strings on the echo line? Or the usage of the opening PHP short tag? Or the usage of "<BR>" instead of "<br/>"?
After pointing out the actual errors, I made a point of adding comments about those things I just mentioned. It was enough to push the answer from "correct" to "impressive", and it scored me a lot of points with the programmers who were reviewing my application. Enough so that they offered me the job! (I eventually turned it down, as I have been seduced by the siren call of the contracting life, and I intend to flex my PHP skills to the benefit of my clients, and not a faceless corporate overlord who dabbles in telemarketing. I need a shower).
So, read on for my Ten PHP Best Practices Tips that will get you a job:
1. Single-quoted strings are your friend. When you surround a PHP string in double quotes, it is subsequently parsed by the PHP interpreter for variables and special characters, such as "\n". If you just want to output a basic string, use single quotes! There is a marginal performance benefit, since the string does not get parsed. If you have variables or special characters, then by all means use double-quotes, but pick single quotes when possible.
2. String output. Which line of code do you think runs faster?
print "Hi my name is $a. I am $b"$$
echo "Hi my name is $a. I am $b"$$
echo "Hi my name is ".$a.". I am ".$b;
echo "Hi my name is ",$a,". I am ",$b;
This might seem weird to you, but the last one is actually the fastest operation. print is slower than echo, putting variables inline in a string is slower than concatenating them, and concatenating strings is slower than using comma-separated echo values! Not only does not-inlining your variables give you a performance boost, but it also makes your code easier to read in any editor that has syntax highlighting (your variables will show up in nice colors). The little-known use of echo as a function that takes a comma-separated list of values is the fastest of them all, since no string operations are performed, it just outputs each parameter. If you combine all this with Tip #1 and use single quotes, you're on your way to some finely-tuned strings.
3. Use single-quotes around array indexes. As you saw in the quiz question above, I pointed out that $x[sales] is technically incorrect! You should quote associative array indexes, like so: $x['sales']. This is because PHP considers the unquoted index as a "bare" string, and considers it a defined constant. When it can't find a matching symbol for this constant in the symbol table however, it converts it to a real string, which is why your code will work. Quoting the index prevents this constant-checking stuff, and makes it safer in case someone defines a future constant with the same name. I've also heard that it is up to seven times faster than referencing an unquoted index, although I haven't tested this. For more on this, see the section called "Array do's and don'ts" in the Array section of the PHP manual.
4. Don't use short open tags. Eww… are you really using these? <? is just bad form. It can cause conflicts with XML parsers, and if you ever distribute code, it's going to annoy the heck out of people who have to start modifying their PHP ini directives to get it to work. There's just no good reasons to use short open tags. Use the full <?php.
5. Don't use regular expressions if you don't need to. If you're doing basic string operations, stay away from the preg and ereg function groups whenever possible. str_replace is much faster than preg_replace, and strtr is even faster than str_replace! Save those crunch cycles… your enterprise applications will thank you.
Bad:
for ($i = 0; $i < count($array); $i++) {
//stuff
}
Good:
$count = count($array);
for($i = 0; $i < $count; $i++) {
//stuff
}
That should be pretty self-explanatory, but it's amazing how many people would rather save a line of code at the expense of performance. If you use a function like count() inside a loop declaration, it's going to get executed at every iteration! If your loop is large, you're using a lot of extra execution time.
7. Never rely on register_globals or magic quotes. register_globals and magic quotes are both old features of PHP that seemed like a good idea at the time (ten years ago), but in reality turned out to be not that great. Older installations of PHP would have these features on by default, and they cause security holes, programming errors, and all sorts of bad practices, such as relying on user input to create variables. Both these features are now deprecated, and everyone needs to stop using them. If you are ever working on code that relies on these features, get it out of there as soon as you can!
8. Always initialize your variables. PHP will automatically create a variable if it hasn't been initialized, but it's not good practice to rely on this feature. It makes for sloppy code, and in large functions or projects can become quite confusing if you have to track down where it's being created. In addition, incrementing an uninitialized variable is much slower than if it was initialized. It's just a good idea.
9. Document your code. You've heard it many times, but this can't be said enough. I know places that won't hire people who don't document code. I even got my previous job after an interview where the VP sat-in with the interviewer and I, where I had brought my laptop in and I was just scrolling through some code I had written for one of my sites. He saw my documented functions and was impressed enough to ask me about my documenting habits. A day later I had the job.
I know a lot of self-declared PHP gurus out there like to pretend that their code is so good that they don't have to spend time documenting it, and these people are full of $largeAnimal poop. Learn docblock syntax, familiarize yourself with some PHP Documentation packages like phpDocumentor or Doxygen, and take the extra time to do it. It's worth it.
10. Code to a standard. This is something that you should ask potential employers about during interviews. Ask them what kind of coding standards they use… PEAR? Zend? In-house? Mention that you code to a specific standard, whether it be your own, or one of the more prevalent ones out there. The problem with loosely-typed languages like PHP is that without a proper coding standard, code tends to start looking like huge piles of garbage. Stinky, disgusting garbage. A basic set of rules that includes whitespace standards, brace matching, naming conventions, etc. is a must-have, must-follow for anyone who prides themselves on their code quality.
That being said, I hate all you space-indenters. I mean, what the hell? 4 space characters as an indent? That's exactly four times as much whitespace to parse as a tab. More importantly, you can set your tab-stops to any value you want if you're using any text-editor more advanced than Notepad, so every developer can having something that they like the looks of. Set it to 4 if you want, or 0 if you're a masochist. I don't care, but you can't do that with spaces! You're stuck with exactly the amount that Mr. Monkey Pants in cubicle 17 decided to put in. So why are spaces so popular? This "4-space indent" standard everyone uses is stupid! Stop it! Stop doing it!
… sorry, pet peeve.
Anyway, I hope these tips are helpful. If you want to impress at a job interview, it's the little details that will get you noticed! Maybe don't rant about your coding standards though.
10条PHP编程习惯助你找工作
过去的几周对我来说是一段相当复杂的经历。我们公司进行了大裁员,我是其中之一,但却体验到了其中的乐趣。我从来没有被开除过,所以很难不去想得太多。我开始浏览招聘板块,一个全职PHP程序员的职位很吸引人,所以我寄去了简历并获得了面试机会。在面试之间,我和其主要的程序员们在咨询电话中聊了聊,最后他们给我出了一套测试题,其中有一道很耐人寻味。
找出以下代码的错误之处:
<?
function baz($y $z) {
$x = new Array();
$x[sales] = 60;
$x[profit] = 20:
foreach($x as $key = $value) {
echo $key+" "+$value+"<BR>"$$
}
}
你能找到几个呢?
如果你发现函数参数列表中少了逗号、“new Array()”是不正确的、行末用了冒号而不是分号、foreach中没有用“=>”及用“+”来连接字符串,那恭喜你,你找到了所有的错误,你已经掌握了PHP编程的基础。
现在我来说说我是怎么回答这道题的。我当然也找出了以上这些问题,但我更进一步。比如,你有没有发现在数组索引里没有用引号将字符串括起来?虽然这不会造成严重错误,但这是一个编码错误。另外,你注意到在echo一行它使用了双引号而不是单引号吗?使用了PHP开始标志的缩写形式?并且没有用“<br/>”而是用了“<BR>”?
在找出了实际错误后,我又在上面找到的问题后面加了注释。这足够让这份答卷从“正确”转变为“发人深省”了,这也给我的申请加了不少分,所以他们决定聘用我。(但最后我拒绝了,因为我喜欢紧凑的生活节奏,并将自己的PHP技能奉献给我的客户,而不是一家涉猎电信市场的公司。我需要一个舞台来大展身手。)
那么接下来就来看看我写的10条PHP编程习惯吧:
1、使用单引号括起来的字符串
当使用双引号来括字符串时,PHP解释器会对其进行变量替换、转义等操作,如“\n”。如果你只想输出一个基本的字符串,就用单引号吧,这样会节省一些资源。当然,如果你需要进行变量替换的,那就必须用双引号了,但其他情况下还是用单引号吧。
2、字符串的输出
你认为以下哪一条语句的运行速度最快?
print "Hi my name is $a. I am $b"$$
echo "Hi my name is $a. I am $b"$$
echo "Hi my name is ".$a.". I am ".$b;
echo "Hi my name is ",$a,". I am ",$b;
echo 'Hi my name is ',$a,'. I am ',$b;
也许这看起来很奇怪,但事实上最后一条的运行速度是最快的。print比echo要慢,在字符串中进行变量替换时会慢,而连接字符串要比用逗号连接来得慢,最后一句则是第一个习惯的体现。所以,不在字符串中进行变量替换不仅会加快程序运行速度,也会让你的代码在任何语法高亮显示的编辑器中显得更为易懂(变量会被高亮显示出来)。很少人知道echo的参数可以用逗号连接,且速度会比字符串连接要来得快。最后再用上第一个习惯,那这条语句就非常好了。
3、在数组索引中使用单引号
正如你在上面的测试题中所看到的,我指出了$x[sales]从严格意义上来说是错误的,索引应该被括起来,即$x['sales']。这是因为PHP会将没有括起来的索引辨认为“裸”字符串,并把它解释为一个常量。当找不到该常量的定义时,才将其解释为一个字符串,所以这条语句才是可运行的。把索引括起来可以省去这部分工作,如果将来正好要用这一字符串定义常量时也就不会有错误了。我甚至听说这样做要快七倍左右的时间,虽然我没有亲自测试过。更多关于这一话题的讨论,请看PHP手册“数组”一章中的的“数组的能与不能”一节。
4、不要使用开始标志的缩写形式
你正在使用这样的符号吗?“<?”是非常糟糕的符号,它会引起与XML解释器的冲突。而且一旦你发布了这些代码,那么使用者就必须修改php.ini文件来打开对此符号的支持。所以实在没有理由去使用这种形式。用“<?php“吧。
5、尽量不要使用正则表达式
在进行常规的字符串操作时,尽可能不要去使用正则表达式(preg和ereg系列函数)。str_replace函数要比preg_replace快得多,甚至strtr函数也要比str_replace来得快。省去这些不必要的麻烦吧,你的老板会感谢你的。
6、不要在循环声明中使用函数
这个问题不单单出现在PHP中,你可以在其他语言的代码中经常看到:
差:for($i=0;$i<count($array);$i++){...}
好:$count=count($array);for($i=0;$i<$count;$i++){...}
这因该很好解释,但许多人就是想少写一行代码而浪费了系统资源。如果在循环声明中使用了count函数,那每次循环都会调用一次。如果你的循环次数很多,那就会浪费非常多的时间。
7、永远不要使用register_globals和magic quotes
这是两个很古老的功能,在当时(十年前)也许是一个好方法,但现在看来并非如此。老版本的PHP在安装时会默认打开这两个功能,这会引起安全漏洞、编程错误及其他的问题,如只有用户输入了数据时才会创建变量等。如今这两个功能都被舍弃了,所以每个程序员都应该避免使用。如果你过去的程序有使用这两项功能,那就尽快将其剔除吧。
8、一定要对变量进行初始化(这里的“初始化”指的是“声明”——译者注)
当需要没有初始化的变量,PHP解释器会自动创建一个变量,但依靠这个特性来编程并不是一个好主意。这会造成程序的粗糙,或者使代码变得另人迷惑,因为你需要探寻这个变量是从哪里开始被创建的。另外,对一个没有初始化的变量进行递增操作要比初始化过的来得慢。所以对变量进行初始化会是个不错的主意。
9、对代码进行注释
这个问题已经提过很多次了,但再多次也不够。我知道有些地方是不聘用不对代码进行注释的程序员的。我在前一次工作面试后和副总、面试官一起浏览我写的代码,当他们对我所做的代码注释印象深刻,还了解了一下我的这一习惯。一天之后,我得到了这个工作。
我知道有些自称为PHP大师的人声称自己的代码写得很好,不需要添加什么注释。在我看来,这些人都是垃圾。学一写注释的规范和技巧,熟悉一下phpDocumentor或Doxygen之类的注释辅助软件,都是值得的。
10、遵循一个编程规范
关于这一点,是你需要在面试中询问你潜在的老板的,问问他们正在使用什么编程规范。PEAR?Zend?内部规范?要提及你正在使用的编程规范,不管是你自己创建的,还是目前普遍流行的一种。对于PHP这种松松垮垮的语言来说,如果没有一个好的编程规范,那么那些代码就会看起来想一堆垃圾。发臭的,令人作呕的垃圾。一些基本的规范包括空格规范、打括号匹配、命名风格等。这对任何一个追求高质量的代码的人来说都是必须的。
有人说:“我讨厌你的4个空格的缩进。”我要说,什么?用4个空格来缩进?这比用制表符过占用3个字符的空间。更重要的是,只要是使用比记事本高级的编辑器,你可以自定义制表符的缩进值。所以每个程序员都可以以其最习惯的方式来看代码。可以时设置为4,也可以设置为0(如果你是个受虐狂)。反正我不在乎,但你就是不能用空格来缩进!
总的来说,我希望以上这些编程习惯可以对你有所帮助。如果你想在面试中留下好印象,只需要一些小细节就可以了。
