Jump to the main content.

Covering all things web, one article at the time.

Want to write for WebD&D? We are looking for writers. Interested? Drop us an e-mail at hi (at) webdosanddonts.com.

Fundamental PHP coding Do’s & Don’ts

Written by Siniša on May 2, 2010.

There are tons of great PHP articles out there. Most of them cover performance tips and general PHP how-to’s. That’s why I’m going to take a different approach here and try to give you some PHP coding guidelines, many of which are just general good programming practices taken from the PHP perspective.

Comment your code in a formal standard

Formatting comments in DocBlock standard offers 3 main advantages to random commenting:

  • It makes comments readable in a standard method encouraging programmers to define and comment on aspects of the code that would normally be ignored
  • It allows external document generators like phpDocumentor to create well formatted and easy to understand documentation
  • It allows some IDEs to interpret variable types and other ambiguities in the loosely typed language and to provide improved code completion, type hinting and debugging

Here is an example of DocBlock comment:

/**
 * A sample function docblock
 * @global string document the fact that this function uses $_myvar
 * @staticvar integer $staticvar this is actually what is returned
 * @param string $param1 name to declare
 * @param string $param2 value of the name
 * @return integer
 */
function firstFunc($param1, $param2 = 'optional')
{
    static $staticvar = 7;
    global $_myvar;
    return $staticvar;
}

Commenting like this may take you some extra time, but it is worth it.

Don’t overuse global variables

… or better yet — try to keep them to the bare minimum if not avoiding them altogether :)

This is true for most (if not all) programming languages. Here’s what Wikipedia has to say on the subject:

They are usually considered bad practice precisely because of their nonlocality: a global variable can potentially be modified from anywhere, (unless they reside in protected memory) and any part of the program may depend on it. A global variable therefore has an unlimited potential for creating mutual dependencies, and adding mutual dependencies increases complexity.

Global variable on Wikipedia

In PHP, global variables are used a little differently than in other languages. They must be declared global inside the function if they are going to be used in that function. I guess it’s a kind of safety mechanism protecting you from unintentionally changing a global variable. But on the other hand if you omit the global declaration by mistake you could end up spending hours on debugging, wondering why the output is not what (you think) it should be. Sounds familliar?

Some of the alternatives to global variables are:

  • a static class, probably implementing a Singleton pattern
  • passing a variable as a parameter

Consider alternative syntax for control structures

When using PHP control structures (if, while, for, foreach, switch) inside your HTML template those curlly brackets can really be hard to follow. Take a look at this HTML template extract:

<div id="fooes">
<?php if ( have_foo() ) { ?>
	<h2>Here are my fooes</h2>
	<?php foreach ( $fooes as $myfoo ) { ?>
		<h3><?php echo $myfoo->title; ?></h3>
		<p class="foo-date">This foo was posted on <?php echo $myfoo->date; ?> by <?php echo $myfoo->author; ?></p>
		<?php if ( $myfoo->is_special ) { ?>
			<div class="special">
				<?php echo $myfoo->content; ?>
			</div>
		<?php } else { ?>
			<div class="not-so-special">
				<?php echo $myfoo->content; ?>
			</div>
		<?php } ?>
	<?php } ?>
<?php } else { ?>
	<h2>Sorry, no fooes available!</h2>
<?php } ?>
</div>

Even in a simple template, like our example here, it’s easy to get confused with those closing brackets. So let’s try to rewrite this using alternative syntax for control structures:

<div id="fooes">
<?php if ( have_foo() ) : ?>
	<h2>Here are my fooes</h2>
	<?php foreach ( $fooes as $myfoo ) : ?>
		<h3><?php echo $myfoo->title; ?></h3>
		<p class="foo-date">This foo was posted on <?php echo $myfoo->date; ?> by <?php echo $myfoo->author; ?></p>
		<?php if ( $myfoo->is_special ) : ?>
			<div class="special">
				<?php echo $myfoo->content; ?>
			</div>
		<?php else : ?>
			<div class="not-so-special">
				<?php echo $myfoo->content; ?>
			</div>
		<?php endif; ?>
	<?php endforeach; ?>
<?php else : ?>
	<h2>Sorry, no fooes available!</h2>
<?php endif; ?>
</div>

If you want a “real world” example take a look at the archive.php template from WordPress default theme.

Avoid using PHP short tag

Although there can be times when doing something like <?=$foo?> can seem like a convenient thing to do, you should resist the temptation and use <?php echo $foo; ?>.

There are several reasons why you should avoid using the PHP short tag, but here are the most important ones:

  • On some shared hosts short tags are turned off so in case of  moving your site you might end up replacing all of your PHP opening tags
  • Avoid the confusion with the XML declaration
  • Short tags will not be supported in future PHP versions

Initialize your variables

Yes — PHP is loosely typed language and no — you don’t have to initalize your variables, but… Initializing variables (and sticking with it’s type from then on) is simply a good coding practice. This will make your code more easy to follow and less error-prone. Especially in larger functions/methods.

There is also a performace benefit since incrementing a initialized variable is much quicker then an uninitialized one.

About the author

Siniša Kolundžić is a wannabe rock drummer and web enthusiast from Croatia. Making his daily bread as a business application developer he always finds the time to contribute to WebD&D.

22 Responses to “Fundamental PHP coding Do’s & Don’ts”

  1. Tom Arnfeld says:

    Interesting!
    Some useful tips here :)

  2. Giovanni says:

    I don’t know
    if (after ten year of C and PHP)
    {
    I will be able to leave curly bracese
    }

  3. fwolf says:

    Sorry, but if you’re using a proper editor with bracket highlighting, after a while the alternative syntax for control structs gets total HORRIBLE and you get lost in them …

    .. so better stick to proper curly brackets, which can be easily resolved using above mentioned bracket highlighting (and if you got a proper editor, it’s also able to do some code folding or letting you hop to the begin / end of the bracket ;)).

    cu, w0lf.

    • mikemick says:

      It’s a matter of preference. Personally, I like using the method in the article because it reads better. In retrospect, when the code get’s complex, brackets, braces, etc don’t hardly read at all. I don’t like having to click every single closing bracket, to see which opening bracket highlights.

      There is nothing wrong with making your code more verbose and easier to read.

  4. aditia says:

    hey thanks for the tips, yeah i agree wordpress has using good php code in html template, you can just explore it

  5. Those are all very excellent tips, I would contend that commenting your code is the most important.

  6. Allen says:

    Thanks for the article. By the way, it’s = it is.

  7. Siniša says:

    @Tom, @aditia, @Jordan, @Allen: Thanks guys, appreciate it!

  8. Siniša says:

    @Giovani, @fwolf: I hear you guys, but I’m not saying ditch the closing brackets completly… Just consider the alternative when you have to nest a lot of control structures inside HTML template which has a lot of switching between PHP and HTML.

    Anyway, thanks for the comments. It’s always good to hear other opinion.

  9. SeanJA says:

    You forgot Don’t use a template engine. It will just make your job harder.

  10. ryan says:

    Flawed article

    “Some of the alternatives to global variables are: a static class, probably implementing a Singleton pattern”

    Singletons are the same thing as global variables…. they come with all the bad that global variables have. Really, it’s the exact same as using a global variable.

    Also, php is not killing (short tags (>?= ?<)). They are perfectly fine to use.

    • g says:

      @ryan Singleton == global? No, a well-constructed singleton can be self-contained in its own class using a static class variable. A few of the big reasons against GLOBALS are they can be easily misplaced (What the hell did I name it? Where did I set it up?) or overwritten. With a singleton, you don’t have to worry about it since it’s attached to a class and unless you’re really sloppy with it, it can’t be overwritten. I just wish some of the people I work with would figure that out.

      When coding open source for the public, you should code to the least-common-denominator (and disregard the poor servers still running PHP4), which for one thing means no short-tags (since they may be disabled on a server) and not requiring obscure extensions.

  11. Runish says:

    Just to clarify….done this a zillion time so far. Short tags are _not_ – i repeat – _not_ going away!

  12. Basil Romero says:

    @ryan Singleton == global? No, a well-constructed singleton can be self-contained in its own class using a static class variable. A few of the big reasons against GLOBALS are they can be easily misplaced (What the hell did I name it? Where did I set it up?) or overwritten. With a singleton, you don’t have to worry about it since it’s attached to a class and unless you’re really sloppy with it, it can’t be overwritten. I just wish some of the people I work with would figure that out.
    +1

  13. Great information and good code. Thanks for sharing.

  14. Matt says:

    Please remove the alternative syntax from this best practices page. First of all it does break bracket balance and it honestly doesn’t look any better if you format your code properly it will look fine and read just as well. My vote is to deprecate the alternative syntax so I don’t have to open a 100k line application that uses only alternative syntax because some web site said it was the right thing to do. At least mention a warning that this breaks balance braces and can potentially be a headache for someone opening your code in the future.

  15. Matt says:

    You also might mention that you should not use mysql_pconnect some people still use it and wonder why after a month the server no longer can connect to sql.

  16. Angle says:

    Oh thank you to all fo sharing such a nice information. As I am new to PHP it is very useful.

Leave a Reply

Spam is bad, mmkay?