English 中文(简体)
PHP specific - clean code, naming conventions and documentation
原标题:

What are some of the best practices for clean code, naming conventions and documentation for PHP?

I see users/people saying this is a bad practice, Example:

// Create an array to hold x values
$arr_x = array();

That this is a unnecessary comment cause the syntax alone explains the functionality. That is should be more of a header comment that describes the script/function functionality rather than the variables/flow of the program. Example

/**
 * Create an array
 */
function create_array() {
   return array();
}

$arr_x = create_array();

// This is just to show the comments and the code is not tested or used except for this example

This has lead me down the path of proper syntax, coding and documentation (The reason for the title naming).

what is acceptable for variable, functions and script naming conventions or is this personal preference?

$varX
function varX()
varX.php

or

$var_x
function var_x()
var_x.php

I m trying to find if there is a standard I should be conforming to. Thanks

最佳回答

There is no standard, just the opinions of developers.

I prefer to have variables delimited by underscores:

$my_var

But for functions I prefer camel-case:

function myFunction() {}

As for comments, yes sometimes comments such as // create array are not required at all, but don t be put off using one liners, they won t slow your script down when it is executed. I like to use one lines to neatly describe each step of a complex script.

As long as your code is readable for you and your fellow developers (others on a project, 3rd part companies etc) then you will be fine.

问题回答

Zend Framework has a PHP coding standard document here that should cover things like how to name variables and functions.

When and how to comment is much less platform-specific. I think a good general rule is to comment on why something is done, rather than how. The code should be written clearly enough to make how obvious. (There are exceptions, of course, such as the use of particularly complex algorithms that may need explanation.)

What s most important is to be consistent. Beyond the basics, like descriptive variable, function, and method names, all that really matters is consistency.

If you don t want to think too hard about it, feel free to use one of the popular coding style guides like the one from the PEAR project, or the Zend Framework standard that JacobM Just posted.

I use codeigniter, here is their style guide.
http://codeigniter.com/user_guide/general/styleguide.html

Find a standard that you like, or the closest match to your existing codebase, that is supported by php_codesniffer - and install that tool - at least then you have a tool at your disposal for checking your code for discrepancies.

One important thing is consistency. Whatever you pick for your development team - any of the standards mentioned above - make sure that EVERYONE in your development organization is sticking to it. Otherwise, code will be very hard to read, and things will be hard to code-review.

Drupal is one of the biggest open source codebase written in PHP.

They must have some good code convention.

http://drupal.org/coding-standards

Coding standards have been changing in php. if you look at the older frameworks they all use Camel case, which in my opinion can lead to errors in the code. it makes sense for a language like java, but not php.

The more recent coding standards and frame works avoid using cammel case , and have a preference for lower_case underscore seperated variable names. eg: fat_yak, rather than fatYak.

The problem with php is that it will accept a new variable that has been undeclared, and since Case is important, it is possible to have two variables with the same name, but different case. Hence inmho it is important to always use lower case with variables, to avoid simple errors, which may go undetected otherwise. The same principle should be extended to method names, as the same issue will be encountered when writing extended classes and overwriting method names. (it is possible to misplace a capital letter and end up with a second function, rather than replacing the original function as you intended.)

I think there are some very fine coding standards out there that are spoiled by this camelCase aspect.

this principle should also be extended to file names. given unix servers differ from windows servers in regards to case, imho many of teh problems can be avoided by always using lowercase. non the less naming classes with a capital starting letter is probably a nessescary evil.

Using CamelCase in class names is fine. If you make a mistake here it will be picked up straight away. In fact using a capital letter at the start of a class is mandatory for your own sanity. (I would name them like this Fat_yak, not FatYak, but i am in the minority on that one, so may keep my mouth shut.. although it would make naming files easier.. eg: Fat_yak.php rather than FatYak.php)

using 4 spaces instead of a tab is a very useful idea, especially if many different editors are used. (the code will look the same on all editors)

everything else is a 50-50 proposition.. and each standard seems to choose one of two options.. This is the disappointing aspect of coding standards, in that a clear leader has not emerged.

eg: 
"true" or "TRUE"

eg:
function blah(){

}

or

function blah()
{

}

This I d call an antipattern. What will you do when there will be some data type change? Will you just change the whole project and maybe many other projects that use your code?

I d rather use simple:

$x
function x()
x.php

JacobM just posted a good PHP standards doc. However, if I m editing or adding on to existing code, I try to follow the style laid out by the previous author.





相关问题
Brute-force/DoS prevention in PHP [closed]

I am trying to write a script to prevent brute-force login attempts in a website I m building. The logic goes something like this: User sends login information. Check if username and password is ...

please can anyone check this while loop and if condition

<?php $con=mysql_connect("localhost","mts","mts"); if(!con) { die( unable to connect . mysql_error()); } mysql_select_db("mts",$con); /* date_default_timezone_set ("Asia/Calcutta"); $date = ...

定值美元

如何确认来自正确来源的数字。

Generating a drop down list of timezones with PHP

Most sites need some way to show the dates on the site in the users preferred timezone. Below are two lists that I found and then one method using the built in PHP DateTime class in PHP 5. I need ...

Text as watermarking in PHP

I want to create text as a watermark for an image. the water mark should have the following properties front: Impact color: white opacity: 31% Font style: regular, bold Bevel and Emboss size: 30 ...

How does php cast boolean variables?

How does php cast boolean variables? I was trying to save a boolean value to an array: $result["Users"]["is_login"] = true; but when I use debug the is_login value is blank. and when I do ...

热门标签