Skip to page content or skip to Accesskey List.
Search evolt.org
evolt.org login: or register

Work

Main Page Content

PHP coding guidelines

Rated 4.03 (Ratings: 10) (Add your rating)

Log in to add a comment
(30 comments so far)

Want more?

 
Picture of pwaring

Paul Waring

Member info | Full bio

User since: June 03, 2002

Last login: June 27, 2008

Articles written: 1

PHP coding guidelines

The guidelines that I follow when writing my PHP scripts; can be helpful to have something like this if you're working on a joint project.

N.B. These are only the guidelines that I personally chose to follow for the code I write. This is not an indication that any other coding styles, guidelines or standards are wrong. Feel free to use this document as a template to manage your own coding guideline and change whatever you wish as you see fit.

Why are guidelines important?

First of all, let's make one point crystal clear: it doesn't matter what your guidelines are, so long as everyone understands and sticks to them. I've worked on a team where the person in charge preferred to put braces following the expression, rather than on a line all by themselves. Whilst I didn't necessarily agree with this convention, I stuck to it because it made maintaining the whole project much easier.

It cannot be emphasised enough that guidelines are only useful if they are followed. It's no use having a definitive set of coding guidelines for a joint programming project if everyone continues to write in their own style regardless. It is arguable that you can get away with different coding styles if every team member works on a different section which is encapsulated and therefore their coding style doesn't affect the other developers. Unfortunately, this only holds true until a developer leaves and someone else has to take over their role.

If you are running a joint project, you might consider putting your foot down and basically refuse to accept any code that does not conform to your published guidelines, regardless of its technical merit (or lack thereof). This may sound somewhat draconian and off-putting to developers at first, but once everyone begins to code to the guidelines you'll find it a lot easier to manage the project and you'll get more work done in the same time. It will require a lot of effort from some of your developers who don't want to abandon their coding habits, but at the end of the day different coding styles will cause more problems than they're worth.

Editor settings

Tabs v. spaces

Ahh, the endless debate of tabs v. spaces. To be honest, I recommend using tabs all the time for the simple reasons that it is much easier to align everything using them, and tabs require less space in a file than multiple spaces. Also, if you set your editor to display a tab character as 8 spaces, but another developer prefers to have them represented as 4 spaces, it doesn't matter in the slightest.

A mention needs to be made of the PEAR project, who insist on using four spaces instead of tabs in their guidelines. If you want to write code for them, just do it in tabs and then do a quick search/replace to change them all to four spaces.

Linefeeds

The three major operating systems (Unix, Windows and Mac OS) use different ways to represent the end of a line. Unix systems use the newline character (\n), Mac systems use a carriage return (\r), and Windows systems are terribly wasteful in that they use a carriage return followed by a line feed (\r\n).

I use simple newlines all the time, because the Windows way just doubles the size of your line breaks and the Mac OS way is technically incorrect in that a carriage return should only return you to the beginning of the line, ala the old typewriter systems.

If you develop on Windows (and many people do), either set up your editor to save files in Unix format or run a utility that converts between the two file formats.

Naming conventions

Variable names

A lot of textbooks (particulary those about Visual C++) will try to drum hungarian notation into your head. Basically, this means having rules such as pre-pending g_ to global variables, i to integer data types etc. Not only is a lot of this irrelevant to PHP (being a typeless language), it also produces variable names such as g_iPersonAge which, to be honest, are not easy to read at a glance and often end up looking like a group of random characters strung together without rhyme or reason.

Variable names should be all lowercase, with words separated by underscores. For example, $current_user is correct, but $currentuser, $currentUser and $CurrentUser are not.

Names should be descriptive, but also concise. Wherever possible, keep variable names to under 15 characters, although be prepared to sacrifice a few extra characters to improve clarity. There's no hard and fast rule when it comes to the length of a variable name, so just try and be as concise as possible without affecting clarity too much. Generally speaking, the smaller the scope of a variable, the more concise you should be, so global variables will usually have the longest names (relative to all others) whereas variables local to a loop might have names consisting only of a single character.

Constants should follow the same conventions as variables, except use all uppercase to distinguish them from variables. So USER_ACTIVE_LEVEL is correct, but USERACTIVELEVEL or user_active_level would be incorrect.

Loop indices

This is the only occassion where short variable names (as small as one character in length) are permitted, and indeed encouraged. Unless you already have a specific counting variable, use $i as the variable for the outermost loop, then go onto $j for the next most outermost loop etc. However, do not use the variable $l (lowercase 'L') in any of your code as it looks too much like the number 'one'.

Example of nested loops using this convention:

<?php
for ( $i = 0; $i < 5; $i++ )
{
    for (
$j = 0; $j < 4; $j++ )
    {
        for (
$k = 0; $k < 3; $k++ )
        {
            for (
$m = 0; $m < 2; $m++ )
            {
                
foo($i, $j, $k, $m);
            }
        }
    }
}
?>

If, for some reason, you end up nesting loops so deeply that you get to $z, consider re-writing your code. I've written programs (in Visual Basic, for my sins) with loops nested four levels deep and they were complicated enough. If you use these guidelines in a joint project, you may way to impose an additional rule that states a maximum nesting of x levels for loops and perhaps for other constructs too.

Function names

Function names should follow the same guidelines as variable names, although they should include a verb somewhere if at all possible. Examples include get_user_data() and validate_form_data(). Basically, make it as obvious as possible what the function does from its name, whilst remaining reasonably concise. For example, a_function_which_gets_user_data_from_a_file() would not be appropriate!

Function arguments

Since function arguments are just variables used in a specific context, they should follow the same guidelines as variable names.

It should be possible to tell the main purpose of a function just by looking at the first line, e.g. get_user_data($username). By examination, you can make a good guess that this function gets the user data of a user with the username passed in the $username argument.

Function arguments should be separated by spaces, both when the function is defined and when it is called. However, there should not be any spaces between the arguments and the opening/closing brackets.

Some examples of correct/incorrect ways to write functions:

<?php
get_user_data
( $username, $password ); // incorrect: spaces next to brackets
get_user_data($username,$password); // incorrect: no spaces between arguments
get_user_data($a, $b); // ambiguous: what do variables $a and $b hold?
get_user_data($username, $password); // correct
?>

Code layout

Including braces

Braces should always be included when writing code using if, for, while etc. blocks. There are no exceptions to this rule, even if the braces could be omitted. Leaving out braces makes code harder to maintain in the future and can also cause bugs that are very difficult to track down.

Some examples of correct/incorrect ways to write code blocks using braces:

<?php
/* These are all incorrect */

if ( condition ) foo();

if (
condition )
    
foo();

while (
condition )
    
foo();

for (
$i = 0; $i < 10; $i++ )
    
foo($i);

/* These are all correct */

if ( condition )
{
    
foo();
}

while (
condition )
{
    
foo();
}

for (
$i = 0; $i < 10; $i++ )
{
    
foo($i);
}
?>

Where to put the braces

Braces should always be placed on a line on their own; again there are no exceptions to this rule. Braces should also align properly (use tabs to achieve this) so a closing brace is always in the same column as the corresponding opening brace. For example:

<?php
if ( condition )
{
    while (
condition )
    {
        
foo();
    }
}
?>

I know that a lot of programmers prefer to put the first brace on the first line of the block they are encoding, to prevent wasting a line. However, I strongly disagree with this as it makes code much easier to read (in my opinion) if braces line up correctly.

Spaces between tokens

There should always be one space on either side of a token in expressions, statements etc. The only exceptions are commas (which should have one space after, but none before), semi-colons (which should not have spaces on either side if they are at the end of a line, and one space after otherwise). Functions should follow the rules laid out already, i.e. no spaces between the function name and the opening bracket and no space between the brackets and the arguments, but one space between each argument.

Control statements such as if, for, while etc. should have one space on either side of the opening bracket, and one space before the closing bracket. However, individual conditions inside these brackets (e.g. ($i < 9) || ($i > 16)) should not have spaces between their conditions and their opening/closing brackets.

In these examples, each pair shows the incorrect way followed by the correct way:

<?php
$i
=0;
$i = 0;

if((
$i<2 )||( $i>5 ))
if ( (
$i < 2) || ($i > 5) )

foo ( $a,$b,$c )
foo($a, $b, $c)

$i=($j<5)?$j:5
$i
= ($j < 5) ? $j : 5
?>

Operator precedence

I doubt very much that any developer knows the exact precedence of all the operators in PHP. Even if you think you know the order, don't guess because chances are you'll get it wrong and cause an unexpected bug that will be very difficult to find. Also, it will make maintaining your program a living nightmare for anyone who doesn't know the precedence tables in so much depth. Always use brackets to make it absolutely clear what you are doing.

<?php
$i
= $j < 5 || $k > 6 && $m == 9 || $n != 10 ? 1 : 2; // What *is* going on here?!?
$i = ( (($j < 5) || $k > 6)) && (($m == 9) || ($n != 10)) ) ? 1 : 2; // Much clearer
?>

N.B. If you are using expressions like the one above you should split them up into smaller chunks if possible, even if you are already laying them out in the correct format. No-one should have to debug code like that, there's too many conditions and logic operators.

SQL code layout

When writing SQL queries, capitialise all SQL keywords (SELECT, FROM, VALUES, AS etc.) and leave everything else in the relevant case. If you are using WHERE clauses to return data corresponding to a set of conditions, enclose those conditions in brackets in the same way you would for PHP if blocks, e.g. SELECT * FROM users WHERE ( (registered = 'y') AND ((user_level = 'administrator') OR (user_level = 'moderator')) ).

General guidelines

Quoting strings

Strings in PHP can either be quoted with single quotes ('') or double quotes (""). The difference between the two is that the parser will use variable-interpolation in double-quoted strings, but not with single-quoted strings. So if your string contains no variables, use single quotes and save the parser the trouble of attempting to interpolate the string for variables, like so:

<?php
$str
= "Avoid this - it just makes more work for the parser."; // Double quotes
$str = 'This is much better.' // Single quotes
?>

Likewise, if you are passing a variable to a function, there is no need to use double quotes:

<?php
foo
("$bar"); // No need to use double quotes
foo($bar); // Much better
?>

Finally, when using associative arrays, you should include the key within single quotes to prevent any ambiguities, especially with constants:

<?php
$foo
= $bar[example]; // Wrong: what happens if 'example' is defined as a constant elsewhere?
$foo = $bar['example']; // Correct: no ambiguity as to the name of the key
?>

However, if you are accessing an array with a key that is stored in a variable, you can simply use:

<?php
$foo
= $bar[$example];
?>

Shortcut operators

The shortcut operators ++ and -- should always be used on a line of their own, with the exception of for loops. Failure to do this can cause obscure bugs that are incredibly difficult to track down. For example:

<?php
$foo
[$i++] = $j; // Wrong: relies on $i being incremented after the expression is evaluated
$foo[--$j] = $i; // Wrong: relies on $j being decremented before the expression is evaluated
$foo[$i] = $j;
$i++; // Correct: obvious when $i is incremented

$j--;
$foo[$j] = $i; // Correct: obvious when $j is decremented
?>

Optional shortcut constructs

As well as the useful increment and decrement shortcuts, there are two other ways in which you can make your PHP code easier to use. The first is to replace if statements where you are assigning one of two values to a variable based on a conditional. You may be tempted to write something like this:

<?php
if ( isset($_POST['username']) )
{
    
$username = $_POST['username'];
}
else
{
    
$username = '';
}

if ( isset(
$_POST['password']) )
{
    
$password = md5($_POST['password']);
}
else
{
    
$password = '';
}
?>

Whilst the above code works and makes it obvious what you are doing, it's not the easiest or clearest way if you want to run through a list of different variables and do a similar thing to all of them. A more compact way would be to use the ternary operator ? : like so:

<?php
$username
= isset($_POST['username']) ? $_POST['username'] : '';
$password = isset($_POST['password']) ? md5($_POST['password']) : '';
?>

I would recommend using the latter notation wherever you are checking assigning a number of variables one of two values depending on a boolean expression, simply because it makes the code easier to scan and also makes it obvious what you are doing without being unnecessarily verbose.

Use constants where possible

If a value is not going to change throughout the execution of your script, then use a constant rather than a variable to define it. That way, if you do change the value by accident, the PHP parser will output an error and allow you to fix the problem, without it causing any unforeseen side effects.

Remember that constants should never be enclosed in strings, either single or double. You must always use concatenation if you wish to include a constant's value in a string.

Turn on all error reporting

A lot of code I've downloaded from the web and tried to use has failed on my machines because the developers switched off the E_NOTICE flag in their PHP configuration for some reason or another. As soon as I bring it onto my system, where error reporting is set to E_ALL (i.e. show all errors, including references to variables being used without being initialised), the PHP interpreter spews out dozens of error messages which I then have to fix before I can proceed to use the script.

What you need to remember as a developer is that the person who uses your script may not have exactly the same php.ini configuration as you so you aim for the worst possible case, i.e. when some awkard person like me has all error reporting enabled. If your code works with E_ALL set, then it will also work with any other error reporting configuration, including when all error reporting is turned off (e.g. on sites where PHP errors are logged to a file instead).

It's not impossible to get scripts to work with all error reporting turned on, because I've managed it for all the code on all the sites I've ever written PHP code for. Admittedly I've not written any major projects such as a CMS, but if you write proper object oreintated code and make sure that each class doesn't produce any errors, you should be able to make your program as a whole run without errors under normal circumstances.

Of course, on a production site you might want to turn off all errors, or at least redirect them to a file, to avoid admitting to users that your scripts are broken in some way (we know that scripts can't handle every possible error, but users often don't see things this way!). That's perfectly fine and in many cases the recommended action to take. So long as your scripts work with all error reporting turned on, it doesn't matter where they are deployed.

Research student, University of Manchester. Plus lots and lots of other stuff.

Portfolio: www.pwaring.com

Current websites:

Shorthand is not readable

Submitted by dusoft on January 6, 2004 - 00:46.

I have a suggestion regarding readability and accessiblity of your code - if using shorthand such as these: $i = $j < 5 || $k > 6 && $m == 9 || $n != 10 ? 1 : 2; // What *is* going on here?!? $i = ( (($j < 5) || $k > 6)) && (($m == 9) || ($n != 10)) ) ? 1 : 2; // Much clearer

code becomes totally unreadable even when you put in between braces.

I would prefer using if or case statements for this as we can always do this more readable for beginners. Remember we are not coding only for ourselves in case of GNU / GPL and not many people out there really know about shorthand...

Actually for those new to PHP, both && and || are misleading.

login or register to post comments

Re: Shorthand is not readable

Submitted by pwaring on January 6, 2004 - 05:33.

Well, that code snippet was intended purely to demonstrate the problems of relying on precedence and why you should explicitly set precedence using brackets. It does also say, under the code, "If you are using expressions like the one above you should split them up into smaller chunks if possible", so if/case statements might be more suited in this case.

With regards to those new to PHP, this article isn't really aimed at them (although I'll be more than happy if PHP developers of any level of expertise take anything positive away from it). It's geared more towards the intermediate/advanced developer who already knows how to code in PHP but may have picked up some "bad" habits along the way. It's not meant to be a tutorial to teach PHP, otherwise I would have gone through concepts such as if-else much more slowly.

login or register to post comments

$bar

Submitted by chaosdb on January 6, 2004 - 18:13.

You might want to put $'s on your bar's:

$foo = bar[example]; // Wrong: what happens if 'example' is defined as a constant elsewhere?
$foo = bar['example']; // Correct: no ambiguity as to the name of the key
…
$foo = bar[$example];

login or register to post comments

Syntax errors

Submitted by pwaring on January 7, 2004 - 07:25.

The syntax errors you pointed out have now been corrected, thanks for the feedback!

login or register to post comments

Forcing compliance?

Submitted by SimonWaltr on January 7, 2004 - 13:37.

Has anyone given any thought to enforcing code standard compliance? I can see not enforcing it on 3rd party software, however my company implemented a standard set a while ago, but it is virtually impossible to enforce because people make mistakes, and typos, or plain forget.

Are there any apps out there that can enforce this? Maybe throw a warning because your brackets don't line up to company standards? Or maybe your function is not documented according to standards? But at the same time third party code would have to be allowed.

Perhaps code rejection from a CVS commit/update? (though subversion, sourcesafe options would need to be implemented as well for a successful project)

Just a thought, but I think distributed development might benifit from something like this.

login or register to post comments

Re: Forcing compliance

Submitted by pwaring on January 7, 2004 - 14:34.

I suppose you could implement some form of regular expression checking on the CVS server that rejected any committed code that didn't adhere to your internal standards.

I don't know of any third party tools offhand that do enforce standards, but I'm sure there are some our there that do just that, either as the main purpose of the program or as an add-on to an existing one.

login or register to post comments

Coding standard

Submitted by skaruzg on January 8, 2004 - 00:42.

I can recommend coding standard - http://alltasks.net/code/php_coding_standard.html

login or register to post comments

enforcing code standard compliance

Submitted by bruno.vernay on January 8, 2004 - 01:57.

You can use : http://www.phpedit.net/products/phpCodeBeautifier/ read : - http://pear.php.net/manual/en/standards.php - http://www.gnu.org/prep/standards_23.html#SEC23 - http://www.phparch.com/discuss/index.php/m/1507/0#msg_1507 - http://www.tiobe.com/standards/index.htm

login or register to post comments

re: skaruzg

Submitted by dusoft on January 8, 2004 - 03:34.

I don't really like some things in coding standards you provided us with.

IMHO is total stupid to put numbers in comparison to the left from = symbol. It's absolutely illogical (and non-standard, too. And there are some other non-standard recommendations...

ADMIN: Posts like these are not helping. If you disagree with something, please give specific criticism and not just "And there are some other non-standard recommendations". We can only improve when we get told what is wrong and get a good reason why you consider it wrong.

login or register to post comments

RE: Alltasks PHP Coding Standards

Submitted by pwaring on January 8, 2004 - 09:03.

Whilst those PHP standards are fairly comprehensive, some of the suggestions won't work properly if you have all error reporting turned on. For example: print "$myarr[foo_bar] world"; // will output: Hello world will flag an E_NOTICE error because the constant foo_bar isn't defined so the parser will assume that you mean the literal value 'foo_var' which could be something completely different.

Secondly, I also agree with dusoft on the point of putting literal values on the left-hand side of the equivalence operator. It's not logical (you're testing to see whether the value of the variable equals the literal value, not the other way round - even though the effect is the same) and it's totally different to the way you make assignments. Finally, literal values aren't meant to be on the left-hand side in the majority of cases, so exceptions should be limited to as few cases as possible.

login or register to post comments

Peace & standards

Submitted by bruno.vernay on January 8, 2004 - 13:11.

I think that we could be more positiv !

First say that Skaruzg works on producing a document and share it, he provides a forum too. Not everybody did that work.

It is not perfect. OK, but there is no need to bite. Just give your advice, knowledge and opinion.

If every one works on his own "standard" : it is no standard anymore ... Standard is all about sharing and conciliate.

We may be diplomate and not only technical to succed.

Of course sometime, there may be no perfect solution, then just provides all the possibility with pro and cons, to let the user make his choice.

I wonder how Skaruzg received your comment ??

login or register to post comments

Re: Peace & standards

Submitted by Martin Tsachev on January 8, 2004 - 14:35.

"Of course sometime, there may be no perfect solution, then just provides all the possibility with pro and cons, to let the user make his choice."

I think that accounts for almost all cases. If people can't agree on using tabs vs spaces how do you agree on brace positions? I don't say I am against standards but there seems to be no place for only one common standard.

login or register to post comments

Re: Peace & standards

Submitted by skaruzg on January 9, 2004 - 02:26.

bruno.vernay: I've put the link only to present alternative method for stardard of coding. It's not my document.

login or register to post comments

Wider standards

Submitted by tupholme on January 10, 2004 - 14:40.

Camel case (LikeThisExampleHere) is generally accepted as the naming convention for object-oriented code, with properties distinguished from methods by having the first word only being all lower case (suchAsThis). It's a good choice as it's both compact and readable.

For procedural code there is no wider standard, so personal preferences such as the one expressed here can apply.

login or register to post comments

What about /* comments */ ?

Submitted by Nepolon on January 13, 2004 - 17:42.

First:
A good article, and it is very difficult to discuss holy wars without inspiring a skermish so don't take that personally. However, I cannot understand how the discussion has gone this far without discussion of meaningful comments being part of a style guide. Any style guide which fails to mention the desired nature and abundance of comments has failed IMHO.

Junior developers frequently scoff at requests to comment their code, and senior developers invariable scoff at junior developers who have this attitude. Human language descriptions of the task being accomplished are a required backup to the PHP code. The PHP code succinctly describes what it is actually doing, and when it is doing the wrong thing, it is not reliably self documenting. Therefore, PHP code is only self documenting when it is perfect and has no bugs. Do the math. And this rant is especially dedicated to all you hard-working Open Source contributors out there...

Secondly:
Placing constants on the left of comparators is an accepted alternative representation, is semanticaly correct in PHP, and is generally a safer style than what may seem more natural. The reason is exactly as one might suspect: it is impossible in many imperative languages to assign an evaluated value that appears on the left to a variable on the right. By placing the variable on the right, coders can be doubly clear when debugging that they intend to make a comparison rather than an assignment.

login or register to post comments

Very helpful article

Submitted by LDS on January 15, 2004 - 08:45.

I learned alot and the article was well-written.

Standards are critical because others will eventually read your code, and writing with standards is simply good communication. So long as you write clearly, it doesn't matter whether you use abbrevations or spell things out.

Further, typos are easier to forgive if, on the whole, the structure is clear. It's a matter of credibility as well: I have looked at a LOT of downloaded open source php code that was poorly written, and dumped it because the anal-retentive side of me wants to re-write the code for later edits,--a colossal waste of time!

Yet, I know that if I have to go into code in a pinch, I'd better be able to find the error quickly. Well-written code, with lots of negative space allows this. Scrunching files for download speed simply isn't a good excuse anymore for not writing clear code that's decently documented....which is the only big item I would have added to this article.

I've taken to documenting my functions, even when they're just for me because then I know where the variables same from, and when the last time the *&^&^ thing worked was. Also, if the function passes variable somewhere else, then I note that too. Since I don't like or use classes, this comes in very handy. I would think with classes it would be absolutely critical, but people don't do it and as a result, the code (though, oh so clever) is hard to follow.

login or register to post comments

Comments

Submitted by pwaring on January 15, 2004 - 08:52.

Can't believe I missed out comments - obviously they are an extremely important part of programming. I'll add some information about them when I next re-write the article. Tools such as phpdoc go a long way to achieving this, but only if developers use them.

login or register to post comments

Re: Comments

Submitted by Martin Tsachev on January 15, 2004 - 10:10.

Comments are really a must but the way you comment to make use of phpdoc is just insane waste of space. Not disk space - visual space. Haven't checked phpdoc recently but last time I did it required many newlines in your comments to work.

login or register to post comments

phpdoc and documenting your code

Submitted by Nepolon on January 15, 2004 - 11:56.

Last I looked, phpdoc is not a substitute for documenting your code, but it does provide an easier reference for large projects and could be used to draw out an API of sorts. As I said in previous comment, the code should be self-documenting (but it will only be if you use good style, ie a guide like this) but that only tells you what the code does, not what it is supposed to do, or why the developer made certain implementation-time choices. Those go into the phpdocs and the std inline comments respectively.

login or register to post comments

New links

Submitted by bruno.vernay on January 29, 2004 - 00:38.

http://gforge.org/docman/view.php/1/2/file2.html It is a bit old. But more important, I mailled the author about this place ... Hope it will avoid the multiplication of standart.

We talk about it but didn't provide explicit link : http://www.phpdoc.de/.

I hope to see a second version with a "references" section. I wonder if a docbook format wouldn't be better than an article on evolt, or both.

And here is a PDF (in french but with the colors, everybody will understand) http://www.zpmag.com/extraits/zpm_2_sample.pdf In fact I post this with the hope that someone can give the mail of the author ("KDO"). It the kind of PDF that shouldn't be made : no arguements, no explanations, not even a mail to post comment.

login or register to post comments

RE: New links

Submitted by pwaring on January 30, 2004 - 09:36.

Bruno, I think you are missing the point of this article. I'm pointing out why standards are important, as well as including my own self-imposed standards as an example of how standards could be written. I'm not suggesting that my article should be used as a universal PHP coding standard document that everyone must adhere to, so it doesn't really matter if someone else has put their standards on the web as well.

I probably will write a second version of these guidelines, although at the moment I have more important things to be working on. Most likely it'll be written in LaTeX with a PDF version produced for easier reading/printing. I don't really know much about DocBook so I probably wouldn't use that format.

login or register to post comments

Comments

Submitted by cs2004 on February 10, 2004 - 00:09.

I think this information is insufficiency. Thank you skaruzg advised very good link http://alltasks.net/code/php_coding_standard.html

login or register to post comments

RE: cs2004

Submitted by pwaring on February 10, 2004 - 00:32.

As I have already said earlier, some of the code in the standards you point to will not work if error reporting is set to E_ALL (which it should be, in my opinion, if you are testing scripts). Also, I am not saying that my article is a set of standards, rather it should be seen as the guidelines I use when coding which you may or may not like to follow. Of course, I'd be delighted if anyone used them as their standards, but I'm not forcing them down anyone's throat and with the comment system on evolt.org people can point out their different ways of implementing their coding guidelines.

login or register to post comments

the point ...

Submitted by bruno.vernay on February 10, 2004 - 01:08.

Of course the point is not to write ONE standard and force everyone to follow. But, you can't say that you just give your example of what you do as if you where alone !!

You are somewhere between the two : you show some possibilities and explain why this or this is better and on which case. Almost all the comments are on why I prefer this, because it allow me to do that, in this case.

I provide links, because it is the point of Internet as well as working together and sharing our work. Wich is just what you did ... not in the mean to provide ONE standard, but to allow people to choose wich standart suits them well, by having many arguments, examples ...

login or register to post comments

Great article

Submitted by anaxamaxan on February 16, 2004 - 00:29.

Thanks Paul for the great article. The point you have made in replies to comments, that all scripts should work in E_ALL error reporting is really important, and perhaps in an article revision should be emphasized alongside the missing bit about human commenting. Oh, and my 2 bits on commenting: Automated commenting can be useful, but it is not, I repeat not a replacement for human comments. Even if you are a solo developer and it is unlikely that anyone else will be working in your code, comments are still invaluable. 9 months later, after making some small tweak per client request, you may find yourself wondering "What on earth was I thinking?

login or register to post comments

Thanks for the article

Submitted by gray_eminence on February 24, 2004 - 15:48.

Thanks Paul. I'm a web developer/design and I'm only beginning to pickup some PHP. I'll never be a professional programmer, but it sure makes things easier to know how to build certain things. What I appreciate is knowing that the standards I've assumed for myself - and based solely on code I've seen in books or downloads - is not totally off-base. Even simple things, such as braces on their own lines make my code much easier to follow. Being a solo developer (so far) and having no formal training, it's just feels good to know I'm developing, at least some, good habbits.

login or register to post comments

Line endings

Submitted by tobyt on February 24, 2004 - 16:00.

You refer to '\n' as the "newline" character. On UNIX, this is ASCII LF (line feed), which (traditionally) advanced the print paper by one line. As you say, '\r' (carriage return, ASCII CR) returned the print head to the left hand margin. (Not all systems use these equivalents for the escape sequences, beware. Typically '\n' is interpreted 'the line ending character on this system', which varies.)

The mechanical behaviour of TTYs and typewriters has little to do with the concept of line termination, however. Either the UNIX LF or Mac CR convention seems rational; UNIX/LF is the obvious choice for files resident on a web server, as it makes possible many server-side operations on the source files of your site. I have needed to edit source on a colocated box in a terminal session (e.g. via ssh login) many many times; this is less convenient if files use non-native line ending conventions.

Many Mac editors are transparent to line endings (BBEdit, MPW Shell).

The Windows CR/LF, while it is an obsolescent sequence with a redundant character from a pedantic point of view, may be a very wise choice if your site is resident on a Windows box (bad luck!) and you need to edit using DOS/Win tools (e.g., in a tight spot, Notepad).

login or register to post comments

Zend Framework PHP Coding Standard

Submitted by acastro on May 26, 2006 - 17:16.

Keeping in mind that "(...) it doesn't matter what your guidelines are, so long as everyone understands and sticks to them." I'd like to recommend the following guidelines: Zend Framework PHP Coding Standard http://framework.zend.com/manual/en/coding-standard.html

login or register to post comments

PHP Coding Guidelines

Submitted by guitarist on July 25, 2006 - 23:02.

I recommend http://www.buxaprojects.com/en/php_coding_guidelines.htm

login or register to post comments

guidlines are important

Submitted by AxelF on April 2, 2007 - 05:23.

I HATE ;-) it when I have to mess around with undocumented and unstructured code from another coder who has never heard of coding guidlines. So Its a necessary coding-basic for everyone of us! Axel

login or register to post comments

The access keys for this page are: ALT (Control on a Mac) plus:

evolt.orgEvolt.org is an all-volunteer resource for web developers made up of a discussion list, a browser archive, and member-submitted articles. This article is the property of its author, please do not redistribute or use elsewhere without checking with the author.