21 Tips to Make Your PHP Code Better

The most used and well documented programming language for web development is PHP, but it has some problems as a language (every language does). The most important problem is it’s too much permissive, and we can make some common mistakes that can hide our program’s behaviour beyond the limit, instead of writing a clean and easy readable code.

The “limit” is something abstract and we can’t draw the line. But there are many other things and habits we can do and get into of right now to be better developers, 20 of those things are right here.

1. The var_dump is your friend

This function lets you know the value of a variable. Yes, I know, it can sounds pretty obvious, but because PHP is a dynamic language the debugging process can be hard ( it could cover a whole tutorial, actually) and just see the value with a function can help us for “debugging” in an easy way.

This is the specification of such an useful function. Just in case you don’t get the point, we can pass it more than one variable!

var_dump

If you are just using this function and not showing anything more you can pass as the first parameter the string “<pre>” and the output will be easier to understand.

2. Measure the time

When we are developing, we all need to know how much is going to “cost”, because that price must be paid by the user and by our server. Actually is very easy, let’s see a way to do this.

<?php
function timer_start() {
	global $timeparts,$starttime;
	$timeparts = explode(" ",microtime());
	$starttime = $timeparts[1].substr($timeparts[0],1);
	$timeparts = explode(" ",microtime());
}

function time_end() {
	global $timeparts,$starttime;
	$endtime = $timeparts[1].substr($timeparts[0],1);
	return bcsub($endtime,$starttime,6);
}
?>

These functions are required and a very clean way to do this. We can have them in a file, include it whenever we need to measure the time and just echo the result. Here is how:

<?php
include('time_helper.php');

time_start();

// here the code you want to measure
echo 'Hi over there!';

echo time_end();
?>

3. Respect your style

Everyone has his own style, the problem comes when sometimes we have to write code together, or worst, a guy after us have to do it, the point is he has no idea about how we think.

An important fact here is our brain learns better through patterns, so if we respect the same style, we have crossed the first door to get a cleaner code. But, what am I talking about when I say style? The following two examples have different style. Take a look at them.

<?php
function test($var1)
{
	if ($var1)
	//Checking if var1 is ok
	{
		echo "Var1 is Ok";
	}
}
$var2=5;
?>
<?php
function test($var1){
	//Checking if var1 is ok
	if ($var1){
		echo "Var1 is Ok";
	}
}

$var2 = 5;
?>

Yes, I know it could look pointless, but the position of comments or braces have to respect a pattern. Remember, our brain learns faster if we do that.

4. Naming with strong meaning

Spiderman, a man who is almost like a spider, easy right? Well, the name of our functions or variables must be too. Whenever we name something we have to think about its functionality and name it accordingly.

You have to be able to have a clue about the role of the function or variable every time you use it. So don’t name a variable with something like “$a” or “$a1”, better “$request_result” or “$first_element”, for example.

5. Research into the field

It’s important, as a developer, know the tools you have on your table. Maybe you are thinking about how to do a function to sort an array because you don’t know if it has already been made. Of course there isn’t a function for every single case, but PHP is growing up, and has got a lot of functions, so Google can comes in handy if you are wondering how to do a common thing in PHP scripts.

You can also download a cheat sheet, which can show you at first sight the power of the tool you are working with.

6. Booleans could be complicated

If you have got a boolean variable, name it in an afirmative way. Just like the first example.

<?php
// Good and cleaner way
$enable = false;
if (!$enable)
	echo "Ok";

// Bad way. This is just if($enable)
$disable = false;
if (!$disable)
	echo 'Not ok';
?>

7. Copy and Paste are developers’ devils

Just two commands can waste a whole morning. I’m not saying we have to reinvent the wheel every time we type, but we always have to read and completely understand the code we are using.

Say we don’t do this, and we see a code similar to the code we want and without even reading it we just put in the middle of our script. Well, if you realize is like putting a spare part in our car without seeing it. If the car breaks down it’s justified, isn’t it?

A program is like a car, so take cares of him, and don’t let anything crosses the door without researching it before.

8. Getters and Setters

A class must respect some patterns too, like our style. A widely extended practice is mark the attributes as privates and if we want to make them public, we make its getter and setter functions.

See the example below, where we don’t want the rest of classes to know who the owner is, but we don’t care about they know the animal’s name, so we use this practice:

<?php
class animal{
	private $owner;
	private $name;

	// Getter
	public function get_name(){
		return $this->name;
	}

	// Setter
	public function set_name($string){
	   $this->name = $string;
	}
}
?>

9. Exceptions are useful

An exception sounds like an ugly thing, in fact every time we’ve got one means something is wrong and we have to fix it. But exceptions in a script can save a lot of time typing code and checking it.

When something can go wrong (almost always) we have to say to someone (the user or other program), at least the error and the reason why it happened. Exceptions can be very useful here, and using them is a must.

10. Divide to rule them all

A common explication for the students at University is that a program is just a set of boxes, the way the boxes have to communicate something is just their output (commonly return).

Well, this definitions is very abstract, but also very useful, we have to think about boxes when we are programming, and if some lines share an objective, we have to make a function and put them there. See this couple of snippets, and judge for yourself.

<?php
// Bad way
$int_array = array(1,9,10,12,7,2,8);

echo "We have to order this array" . "<br />";
foreach($int_array as $value){
	echo $value . "<br />";
}

sort($int_array);

echo "The output is:" . "<br />";
foreach($int_array as $value){
	echo $value . "<br />";
}
?>

And the good way:

<?php
// Good way
$int_array = array(1,9,10,12,7,2,8);

function print_array($array){
	foreach($array as $value){
		echo $value . "<br />";
	}
}

echo "We have to order this array" . "<br />";
print_array($int_array);

sort($int_array);

echo "The output is:" . "<br />";
print_array($int_array);
?>

Of course this is a fool example, because there is a way to do this with some built-in functions (var_dump, for instance), and the script doesn’t do too much work, but the point here is you can see the function “print_array” is saving us writing again the same code and the script, at first sight, looks cleaner.

11. Coding is important

Even essential if in your language there are characters like é, ó, ñ…etc. And not because of the code itself, the key are the comments or some html if you are printing it from a PHP script.

If you change the coding you can create a mess, so every time you are starting or modifying a project you need to check your editor is using exactly the same coding than the project.

I could say just don’t use weird symbols, but it’s not always possible, so be careful.

12. Comments are as important as the code is

I don’t want you to think I’m crazy, but imagine you develop a complex script, without a single comment, if someone is going to reuse it some months later, even you, and an error comes up, fixing the problem is going to take a lot of time just trying to understand the code plus fixing the problem itself.

There is a way to comment which can helps, because it’s very extended and almost every developer understands. You can see all the docs at the conclusion, but basically we’ll have some “special parameters” starting with @, like @see to refer another function, @return to specify the type of the the variable the function is going to return….etc. (You can see all of them in the link at the conclusion)

A good thing about using this format is you can use a tool and export the documentation as a pdf, html or another file, even from the IDE itself you are using (most IDE’s can do this).

13. Be independent

Your code must be a box, and a box doesn’t care about the rest of boxes, so your functions and classes shouldn’t do.

When we write a class we have to think the only way the user has to know something which could happen inside our class is up to us, so we have to do it as better as we can, and make developers’ life easiest (not only ours).

The better thing we can do is making a “map” of errors, and name them with a code and a description. When we have got an exception we return the specified error code. Of course our decisions aren’t standard, so we have to explain the code we’ve invented in the comments

14. An interface is a gift

When we have got a class, and the functions return really useful messages, we are very very lucky, because most developers returns values almost cryptic, and there is no reason apart from laziness to do this.

So every time we have to return something, or display a message, think the best and cleanest way to do that.

15. Official documentation is the only reliable source

Internet is a huge source of information, but in technical stuff, we have to be very carefully and don’t trust anyone, actually if you have got a doubt about a function, which is perfectly usual, it’s better looking up only in the official site.

documentation

16. Use of variables

In a programming language where we declare a variable with just a line, there is a risk of having too much and some pointless variables.

That’s exactly what happens in PHP when our program starts to grow. We should have variables, apart from well named, with a well known role in the script, and if we use an “aux” variable, taking care of not reusing it.

It’s not about the number of variables we can have, it’s about we need to know them all very well, and the reason why they exist.

17. Family is cool

At least in a programming context. PHP is an OO language, so not using heritage in our programs it’s almost an offense for an object oriented language like PHP. Let’s see how to do it, in the first example we can see the bad way:

<?php
class Person
{
    private $givenName;
    private $age;
}

class Employee
{
    private $givenName;
    private $age;
}
?>

And the good way should be something like:

<?php
abstract class Person{
    private $givenName;
    private $age;

	// Getters and setters
    public function set_givenName($name){
        $this->givenName = $name;
    }

    public function get_givenName(){
        return $this->givenName;
    }

    public function set_age($age){
        $this->age = $age;
    }

    public function get_age(){
        return $this->age;
    }

    public function say_hello(){
        echo("I am ");
        $this->print_data();
    }

	// The son will define this function according to its features
   	abstract public function print_data();
}

class Employee extends Person{
    private $role;

	// Getters and setters
    public function set_role($r){
        $this->role = $r;
    }

    public function get_role(){
        return $this->role;
    }

    /*This class have all the public and protected methods from
	the class Person*/
    public function print_data(){
        echo($this->getRole() . " " . $this->get_givenName() . " and I am " .
            $this->get_age() . " years old");
    }
}
?>

18. Functions should be small

If you have got a function where you need to scroll down to see its end, probably you should be thinking how to split it into smaller functions.

19. Frameworks can save you a lot of work

Frameworks are friends who can make for you the dirty work. There are many of them, probably the most used ones are CodeIgniter, Zend or CakePHP, but it’s up to you watch some screencast and study some tutorials to choose the one which should be better for the project we are working on.

If you are starting with frameworks in PHP I recommend you CodeIgniter, it has a great documentation, and develop with it it’s very easy.

CodeIgniter can save you a lot of work

20. Regular expressions are always useful

In every project, if it’s a little bit big, regular expressions will always come in handy.

Since removing repeated words in a text to extracting data from a raw format are only some tasks very easy to do with regular expressions. PHP has a set of functions to do that and know regular expressions and this functions can save you a lot of time, and even make the code cleaner.

21. Common sense above everything

This advices are only useful if you understand them, and try always to use your common sense. How to name variables, or comment the code are just some task where you should be using your common sense, so don’t forget we program for computers but also for human beings.

Conclusion

Like everything else in life you should learn as much as you can about the tools you are working with, and it takes a lot of time to become a better developer in any programming language, so be patience and remember, common sense and documentation are your best allies.

Geary Interactive agency is the leading Real Results digital marketing agency that provides nationally recognized, full service capabilities in a performance driven model. Download Windows 8 Themes

Sign up for Testking 220-702 professional training to learn how to make your PHP code better. Download Testking 70-647 php tutorials with expert Testking 70-290 study guides to become expert.

This entry was posted on Friday, April 23rd, 2010 at 07:20 and is filed under Tutorials. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

I'm from Spain. I've been working in an Internet company for more than a year, I love everything about Internet, from designing to PHP.

About the author Published by Jose

16 Responses »

  1. Great tips and tricks to anyone using PHP, by last count it us a HUGE amount of people.

  2. Good tips 🙂

    I preffer a true debugger rather than using var_dump, however. Or FirePHP, in any case.

    By the way, regular expressions are a great tool, but they are frequently overused. As Jamie Zawinski said:

    Some people, when confronted with a problem, think “I know, I’ll use regular expressions.” Now they have two problems.

  3. Thanks guys, really appreciate it 😉

    @Jordan Walker. By the way, there is a top of programming languages from TIOBE. You can see it here.

    @Zootropo. According to debugging PHP, of course it’s better an actual debugger, but it’s configuration is hard. And about regular expressions I have to say I don’t agree with you. It’s very difficult thing to learn, but once you do it’s power is amazing. I think the problem is they are more unknown than overused, the same thing happens with Javascript, pointers…etc. 🙂

  4. 1.
    get a debugger
    error_log( print_r( $var , true ) ); is your friend
    var_dump is normally a last resort, var_dump doesn’t hit all dimensions of an array and has limits, print_r does not

    2.
    microtime() has a parameter so you can get is as a float – microtime(true)
    globals are generally anti-encapsulation, far better to write as a timer/report class with static method access

    3.
    we’ll be calling that coding standards and “php code sniffer” can really help you out, if you can try to adopt a well known coding standard such as zend coding standards

    4.
    definately, a well named variable can alleviate the meaning for many descriptive comments.

    5.
    worth adding that the php general news group is a very good resource for research, feedback and problem solving.

    6.
    neither $enable or $disable is any better, what’s important is that you make scripts and functions exit as quickly as possible thus:

    $authorised = false;
    // some code to check if action is authorised
    if( !$authorised ) {
    return false; // or throw new Exception('not authorised') or suchlike.
    }
    // continue processing

    7.
    copy and paste is pure evil, in addition to the reasons you mentioned, it indicates that we are not making re-usable code, wrap the code in a function / class and call it from all the places you need

    8.
    I can’t express in how many ways that’s wrong mate, would need write a full post to explain, suggest you google getters and setters and do some reading 🙂

    9.
    Exceptions are very useful! the SPL lib in php provides most of the common ones you’ll need

    10.
    functions, methods, reusable code

    11.
    character encoding*

    12.
    just to clarify that you are reffering to PHPDoc, code documentation, JavaDoc for PHP, http://www.phpdoc.org/ and link at the foot of your post of course.

    12.
    you have two 12’s 😉 would be good to read http://en.wikipedia.org/wiki/Object_oriented and go from there 🙂

    13.
    ??? read http://en.wikipedia.org/wiki/Object_oriented and check what an interface is

    14.
    Yes! the php documentation is critically important

    15.
    use variables when something varies, use use static variables when something varies but is always there, use constants when something is constant – best way to learn is to remove all globals from your scripts and go from there

    16.
    family?? http://en.wikipedia.org/wiki/Object_oriented : Inheritance and Abstraction; aside: all your examples are of “Transfer Objects” (also called Data Transfer Objects (DTO) and Value Objects (VO)

    17.
    functions (and methods) should do one perfectly encapsulated little task, and deal only with that task, if it’s doing more than one you have a problem, see seperation of cross cutting concerns and.. well the point of programming 😉

    18, 19, 20 all fair enough, worth pointing out that Zend framework is a nice collection of modules for doing different things where you can use one or more of them, and the rest are MVC frameworks, they don’t really compliment and enhance your applications, rather they take it over and get you making things with a framework rather than making apps yourself – still rather useful in scenarios (especially presentation tier).

    all meant in the best possible way 🙂

    nathan

  5. @Nathan. Hello and thank you, I really appreciate the comment. Let me write the reply point by point:

    Point 4, 5, 7, 9, 10 and 17 we agree so I won’t say anything more about them 🙂

    1.
    The reason I’ve said to use var_dump is because sometimes installing a debugger can be hard. In a usual code var_dump is pretty enough, and sometimes is more comfortable because you can type 20 variables in the same line.

    2.
    That function is a little bit old, but, yes, that parameter make things easier. According to the file, of course it’s better having a class, but it’s just an example and the reason why I put those functions in a file is just for making the final code cleaner.

    3.
    The problem is as developers we come from many languages, and if we are used to develop with a style it’s difficult to change it. Standards are ok, but getting used to them can be a long process. With my advice I just meant we should respect a pattern, not forgetting about standards.

    6.
    I suspect we are not talking about the same thing here. The point is to notice that we usually use “two false” when it’s easier just use a true. I’m not talking about the meaning of enable or disable.

    8.
    Actually I haven’t shown the actual point of having getters and setters, it was just the syntax. But having setters and getters can be useful for having a password where users can set it but not seeing its content, having a username where you can get the value but not setting it…and many others. But it’s perfectly correct, of course you can generate with a function dynamic setters and getters, but that’s a little bit harder and I just wanted to show the “classic” way.

    11.
    Character encoding is the correct term, but actually it seems clear when I’m talking about � characters in the next paragraph.

    12.
    I don’t know if you’re trying to say I don’t know OO, or just putting a link. Here I meant that when we build classes we have always to try make them as independent as possible, but when we have someone’s classes, then everything can happen 🙂 and checking exceptions or errors coming from that class is a must.

    About the two 12’s sorry, it was my mistake, and thank you for letting me know it.

    13.
    I thought when I was writing this that “interface” could be misunderstood. I meant interfaces as in an API or a control panel, that means methods which allow us to access to the class and give us some kind of responses. Not the OO term of interface, which is a very different thing.

    15.
    Good advice! But I was just trying to notice that we have to take care of the variables we are using.

    16.
    Family is just a term to mean we have to use the Object Oriented feature that PHP has. Of course I could put a lot more examples but the one I put is related and based on that feature. Perhaps I had to put another showing how to use the abstract concept in PHP.

    18.
    I think we should know how to do a thing if we are using a class which does. That means if we are using a framework as CodeIgniter we should be able to develop all the framework (or at least the part we are using) by ourselves and using the framework is just for saving time. Of course sometimes it’s better think about what we need and if we really have to use a framework for that.

    As I’ve said before, thanks for the comment!

  6. And if you are using framework it’s better to follow the framework coding style, for example codeigniter and cakephp have a different coding style, maybe this is only simple thing, but sometimes make me confuse if the coding style not consistent

  7. @aditia. Yes, actually it’s better to follow the style of the project where we are working on. If we work on a huge project and we are new there we should see its style and try to follow it, because other coders’ll thank us. Thanks for the comment!

  8. cool, I almost understood everything))

  9. @Stasovsky. If you don’t get something, just let me know and I’ll try to explain it better 😉

Trackbacks

  1. 20 tips pour mieux coder en PHP | KubX