View Full Version : PHP Best Practices (no replies here please!)

02-23-2007, 06:21 PM
Hello there, all you mad PHP coders out there. I am starting this thread in the hopes that it will turn out really helpful to those wishing to make their experience with coding in PHP more efficient and practical. As we all know, there are a hundred different ways to do the same thing, but some solutions are better than others. That's what this thread is for. My wish is that this would turn into a sticky, but we'll see how it goes.

This thread is specifically for me to post finished "Best Practices" (BP) discussions. I would ask that all discussion of "Best Practices" be kept to the PHP Best Practices - Discussion (http://www.codingforums.com/showthread.php?t=108161) thread. In other words, please don't post ANYTHING to this thread, but instead, use the discussion thread. I can't enforce this, of course, but I would ask it in the interest of organization.

For each BP post, the title at the top of the post is the subject of the BP. I will number the responses/websites from people and link the number to their post/website. I also believe in giving credit where credit is due, so credit will be given at the bottom of each response/website.

If there is something on this thread that is inconsistent, incorrect, or not the best practice, please post it on the discussion thread (http://www.codingforums.com/showthread.php?t=108161), not this one.

I am going to keep this thread up to date by posting new BP and editing already posted BP.

I hope you find this thread very helpful on your continued learning journey through PHP. Good luck!

02-23-2007, 06:27 PM
[1 (http://www.codingforums.com/showpost.php?p=537734&postcount=8)]
A pretty basic one. Always use:




Because if you are working for a client or your server doesn't have php_short_tags on, your code will be broken.

[thanks to Webmonkey (http://www.codingforums.com/member.php?u=33525)]

[2 (http://hudzilla.org/phpwiki/index.php?title=Distinguishing_code_blocks)]
Although <? and <% are available for use to enter PHP mode, their use is not encouraged for several reasons:

They are not enabled by default
They may not be available on other machines
<? is not XML-compliant
Always, always, always use <?php. Always - with no exceptions!

[from http://hudzilla.org/phpwiki/index.php?title=Distinguishing_code_blocks]

02-23-2007, 06:35 PM
[1 (http://www.codingforums.com/showpost.php?p=537482&postcount=2)]
Use switch() in preference to if() anytime you can. To be able to refactor a bunch of ifs as a switch (a) they must all test the same subject and (b) they must test for single values (==) and not ranges (<, >, <=, >=, != [although one of these can often be covered by the default case])

If the goal of the chain of ifs is to assign a single variable different values depending on the conditions *and there are no side effects of testing the conditions* it should be expressed as ternary instead of as if or else. Ternary for assignment is idiomatic in many languages, inc. PHP.

[thanks to ralph l mayo (http://www.codingforums.com/member.php?u=28822)]

[2 (http://www.codingforums.com/showpost.php?p=537517&postcount=3)]
To get around single values or equality used in switch(), you can also use:

case $cond && $cond2 :/*blah*/;

[thanks to firepages (http://www.codingforums.com/member.php?u=4)]

02-23-2007, 06:46 PM
[1 (http://www.codingforums.com/showpost.php?p=537482&postcount=2)]
Prefer to fetch an array when it would not compromise readability (when 1. you're only selecting 1 or 2 fields and 2. when they'll go out of scope quickly, so it doesn't particularly matter what they are named). Another good time to fetch the array is when you're going to assign the results to member data right away, so they'll get meaningful names without the need of associating with the column names.

[thanks to ralph l mayo (http://www.codingforums.com/member.php?u=28822)]

02-23-2007, 09:03 PM
[1 (http://www.codingforums.com/showpost.php?p=537517&postcount=3)]
While the use of eval() is something that has set off many a flame war with equally capable proponents, I personally fall on the side that thinks that eval() is inherently evil. Extract() is a no-no (though I think there can be little argument there).
[thanks to firepages (http://www.codingforums.com/member.php?u=4)]

[2 (http://www.codingforums.com/showpost.php?p=537727&postcount=7)]
Just as in JavaScript, I have not found a single use for eval. This function can be safely ignored.
[thanks to aedrin (http://www.codingforums.com/member.php?u=46155)]

[3 (http://www.codingforums.com/showpost.php?p=537482&postcount=2)]
Don't use extract() for anything. It seems it was made for people incapable of understanding hashes.
[thanks to ralph l mayo (http://www.codingforums.com/member.php?u=28822)]

02-24-2007, 08:09 PM
[1 (http://www.codingforums.com/showpost.php?p=537864&postcount=17)]

global $envCode;
Best practice: Avoid 'global' at all costs. It pollutes the global scope and allows for bad programming. If you need to define whether it is a test environment, do it like this.

define('DEBUG', true);

if (DEBUG) {
echo "var=".$var;
}[thanks to aedrin (http://www.codingforums.com/member.php?u=46155)]

[2 (http://www.codingforums.com/showpost.php?p=537914&postcount=20)]
About the global thing...

I agree that the accepted "best practices" is not to use them, but when something is actually global, such as an environment variable, then my opinion is they are ok.

But I do agree, using a "constant" rather than the keyword "global" is a better practice.
[thanks to Fumigator (http://www.codingforums.com/member.php?u=29634)]

[3 (http://www.codingforums.com/showpost.php?p=537931&postcount=22)]
The superglobals $_GET,$_POST,$_ENV etc are already global assuming you reference them that way, no need for globals at all.
[thanks to firepages (http://www.codingforums.com/member.php?u=4)]

02-24-2007, 08:25 PM
There is no perfect, exact way to style your code. So if someone tells you an exact way to style your code, look them in the eye and say with emphatic confidence in your voice, "Suck it."

There are many ways to organize your code, and many of them are pretty good. To make your code look organized, you can use tabs to indent levels of your code, or you can use spaces. When using curly brackets, you can put them on the same line as the statements, or you can put them on the next line. There are positives and negatives to just about every way of styling your code, so know what they are, and choose one.

Coding Styles
Instead of me typing out a whole explanation of the positives and negatives of using this or that coding style, I'm going to refer to two sites that have already done this in great detail. Remember, these are suggestions, not the exact way you have to do things.

Braces {} Policy:

Indentation/Tabs/Space Policy:

Comment, Comment, Comment!:

If/Then/Else Formatting:

Switch Formatting:

Use of continue, break and ?:

More Formatting Conventions:

As you can see, there is no right way. The biggest thing you should be concerned about is being consistent and clean. Find a good way to style your code, so you and others can look at your code and easily see what's going on. And then do it...consistently. Trust me, you'll be thankful later on when you have to go back and do edits to the code.

02-24-2007, 08:36 PM
The most important thing I could tell you about naming standards for variables is to be descriptive. It is much, much better to name a variable that contains someone's first name $first_name instead of $a. $a doesn't tell you anything about what it contains. It would be appropriate to use $a for a variable that is holding temporary information (such as a query), but overall, try to be as descriptive as possible.

Variable Names
When you give a variable a name, try to follow these basic principles:

Make your variable names all lowercase.
Insert _ instead of spaces (e.g. use $first_name instead of $FirstName).
Try to keep your variable names as short as possible, while maintaining clarity of what the variable holds. A general maximum number of characters is about 15.

Variable Names: http://www.dagbladet.no/development/phpcodingstandard/#stacknames
Variable/Function Naming: http://area51.phpbb.com/docs/coding-guidelines.html#namingvars

Class Names: http://www.dagbladet.no/development/phpcodingstandard/#classnames
Class Library Names: http://www.dagbladet.no/development/phpcodingstandard/#classlnames
Class Attribute Names: http://www.dagbladet.no/development/phpcodingstandard/#attrnames

Function Names: http://www.dagbladet.no/development/phpcodingstandard/#cnames
Variable/Function Naming: http://area51.phpbb.com/docs/coding-guidelines.html#namingvars

To read more about naming conventions for variables, classes, functions, etc., here are some links:


02-24-2007, 09:27 PM
There are two different ways to quote strings in PHP - either with single quotes or with double quotes. The main difference is that the parser does variable interpolation (you can use $variables in the string without doing anything special) in double-quoted strings, but not in single quoted strings. Because of this, you should always use single quotes unless you specifically need variable interpolation to be done on that string. This way, we can save the parser the trouble of parsing a bunch of strings where no interpolation needs to be done.

Also, if you are using a string variable as part of a function call, you do not need to enclose that variable in quotes. Again, this will just make unnecessary work for the parser. Note, however, that nearly all of the escape sequences that exist for double-quoted strings will not work with single-quoted strings. Be careful, and feel free to break this guideline if it's making your code easier to read. Examples:

// wrong
$str = "This is a really long string with no variables for the parser to find.";


// right
$str = 'This is a really long string with no variables for the parser to find.';


// Sometimes single quotes are just not right

$post_url = $phpbb_root_path . 'posting.' . $phpEx . '?mode=' . $mode . '&amp;start=' . $start;

// Double quotes are sometimes needed to not overcroud the line with concentinations

$post_url = "{$phpbb_root_path}posting.$phpEx?mode=$mode&amp;start=$start";

In SQL Statements mixing single and double quotes is partly allowed (following the guidelines listed here (http://area51.phpbb.com/docs/coding-guidelines.html) about SQL Formatting), else it should be tryed to only use one method - mostly single quotes.
[from Coding Guidelines (http://area51.phpbb.com/docs/coding-guidelines.html)]

It is a good idea to use single quotes when you are echoing HTML code. It is much easier to use single quotes because you don't have to escape all the double quotes you use:

//single quotes allow you to use double quotes with the attributes in the HTML code

echo '<div id="content">Hello there.</div>';

//if you used double quotes, you would have to escape all of them

echo "<div id=\"content\">Hello there.</div>";

And here's how to use variables while using single quotes or double quotes:

/* with single quotes, you need to use what's called "concatenation" (stop the string
with a ' and use a . to link strings together...then you can start back the string again
(if you need to) with another . and then a ') */

echo 'The name of my company is ' . $company_name . ' and my name is ' . $first_name;

/* since double quotes allow variable interpolation, you can use a $variable inside double
quotes easily */

echo "The name of my company is $company_name and my name is $first_name.";

/* if you need to, you can put curly brackets around the variable in the double quotes to
make sure nothing jacks with it */

echo "The name of my company is {$company_name} and my name is {$first_name}.";