Five Good Habits of PHP Programming_PHP Tutorial
根据具体的情况,一般的开发人员往往比优秀的开发人员的效率低 10%~20%。优秀的开发人员的效率更高,因为他们拥有丰富的经验和良好的编程习惯。不良的编程习惯将会影响到效率。本文通过展示一些良好的编程习惯,帮助您成为更优秀的程序员。 这些良好的编程习惯不仅能提高效率,还能让您编写出在应用程序的整个生命周期中易于维护的代码。编写出来的代码可能需要大量的维护;应用程序的维护是一笔很 大的开支。养成良好的编程习惯能够提高设计质量(比如模块化),从而使代码更加容易理解,因此维护就更加容易,同时也降低维护成本。 不良的编程习惯会造成代码缺陷,使其难以维护和修改,并且很可能在修改时又引入其他缺陷。以下是 5 个良好的编程习惯,能够帮助 PHP 代码避免这些缺陷: ◆使用良好的命名。 ◆分成更小的部分。 ◆为代码添加注释。 ◆处理错误条件。 ◆切忌使用复制粘贴。 下面将详细介绍这些习惯: 使用良好的命名 使用良好的命名是最重要的编程习惯,因为描述性强的名称让代码更加容易阅读和理解。代码是否好理解取决于是否能在未来维护它。即便代码不带有注释,如果它很容易理解,将大大方便日后的更改。这个习惯的目标是让您编写的代码像书本一样容易阅读和理解。 不良习惯:含糊的或无意义的名称 清单 1 中的代码包含过短的变量名、难以辨认的缩写词,并且方法名不能反映该方法的功能。如果方法名给人的感觉是它应该做这件事情,而实际中它却做另外的事情,这将带来严重的问题,因为它会误导人。 清单 1. 不良习惯:含糊的或无意义的名称 <?php function getNBDay($d){ $day = 5; $nextDay = getNBDay($day); echo ("Next day is: " . $nextDay . "n"); ?> 清单 2 中的代码体现了良好的编程习惯。新的方法名具有很强的说明性,反映了方法的用途。同样,更改后的变量名也更具说明性。惟一的保持最短的变量是 $i,在本清单中,它是一个循环变量。尽管很多人不赞同使用过短的名称,但在循环变量中使用还是可以接受的(甚至有好处),因为它明确表明了代码的功能。 清单 2. 良好习惯:说明性强并且简洁的名称 <?php 分成更小的部分 It will be easier for you to focus on solving one problem before continuing with programming. If you continue to program while solving an urgent problem, the function will become longer and longer. In the long run, this isn't a problem, but you'll want to remember to go back and refactor it into smaller pieces. Refactoring is a good idea, but you should make a habit of writing shorter, more focused code. Short methods can be read in one window and are easy to understand. If a method is too long to be read in one window, it becomes difficult to follow because you can't quickly follow the entire idea from start to finish. When building methods, you should get into the habit of having each method do only one thing. This is a good habit because: first, if a method only does one thing, then it is more likely to be reused; second, such a method is easy to test; third, such a method is easy to understand and change. Bad Habit: Too Long Method (To Complete Many Things) Listing 3 shows a long function with many problems. It does a lot of things, so it's not compact enough. It's also easier to read, debug, and test. Things it does include iterating over a file, building a list, assigning values to each object, performing calculations, and more. Listing 3. Bad habit: too long functions <?php function writeRssFeed($user) // Query $result = mysql_query($query, $link);
switch($d) {
case 5:
case 6:
case 7:
return 1;
default:
return ($d + 1);
}
}
良好习惯:说明性强并且简洁的名称
define (MONDAY, 1);
define (TUESDAY, 2);
define (WEDNESDAY, 3);
define (THURSDAY, 4);
define (FRIDAY, 5);
define (SATURDAY, 6);
define (SUNDAY, 7);
/*
*
* @param $dayOfWeek
* @return int Day of week, with 1 being Monday and so on.
*/
function findNextBusinessDay($dayOfWeek){
$nextBusinessDay = $dayOfWeek;
switch($dayOfWeek) {
case FRIDAY:
case SATURDAY:
case SUNDAY:
$nextBusinessDay = MONDAY;
break;
default:
$nextBusinessDay += 1;
break;
}
return $nextBusinessDay;
}
$day = FRIDAY;
$nextBusDay = findNextBusinessDay($day);
echo ("Next day is:" . $nextBusDay . "n");
?>
我们鼓励您将大的条件拆分为一个方法,然后用能够描述该条件的名字命名方法。这个技巧能够提高代码的可读性,并且能够将条件具体化,使之能够被提取甚至重用。如果条件发生变化,更新方法也很容易。因为方法拥有一个有意义的名字,所以它能反映代码的用途,让代码更容易阅读。
{
// Get the DB connection information
// look up the users preferences...
$link = mysql_connect( mysql_host, mysql_user, mysql_password)
OR die(mysql_error());
$perfsQuery = sprintf("SELECT max_stories FROM user_perfs WHERE user= %s",
mysql_real_escape_string($user));
$max_stories = 25; // default it to 25;
if ($row = mysql_fetch_assoc($result)) {
$max_stories = $row[max_stories];
}
// go get my data
$perfsQuery = sprintf("SELECT * FROM stories WHERE post_date = %s",
mysql_real_escape_string());
$result = mysql_query($query, $link);
$feed = "<rss version="2.0">" .
"<channel>" .
"<title>My Great Feed</title>" .
"< link>http://www.example.com/feed.xml</link>" .
"<description>The best feed in the world</description>" .
"<language>en-us </language>" .
"<pubDate>Tue, 20 Oct 2008 10:00:00 GMT</pubDate>" .
"<lastBuildDate>Tue, 20 Oct 2008 10:00:00 GMT </ lastBuildDate>" .
"<docs>http://www.example.com/rss</docs>" .
"<generator>MyFeed Generator</generator>" .
"
"<ttl>5</ttl>";
/ / build the feed...
while ($row = mysql_fetch_assoc($result)) {
$title = $row[title];
$link = $row[link];
$ description = $row[descript

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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

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

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

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

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

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

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.
