20 things that make a PHP programmer different


PHP is the most popular language for writing server-side code. The same goal can be achieved on it in several ways: you can design a beautiful and easily maintainable system, or you can quickly cobble together pieces of code from Stack Overflow without worrying too much about such things as design rules and code readability.

Of course, even if you’re not a development guru yet, you’ll still want to write code that won’t make others cry. Tproger will help you out – this article contains 20 tips, each of which will help you improve the readability of the code and for following which you will be thanked later. And in the long run, diligently following these tips will help you move closer to the status of an experienced and attentive developer.

Use <?php

Don’t use <? ?> and other ways of placing php scripts in the file. Yes, maybe everything works for you, but on another server – not a fact. On some servers, short tags are disabled altogether. Play it safe, just use <?php. And by the way, do not put a closing php tag – this is a sign of bad taste. Also, a closing tag at the end can lead to unexpected problems associated with an accidentally inserted space or newline at the end of the output.

<? … ?> // Wrong

<?php … // Right

<?=$Var?> // Wrong

<?php echo $Var // Correct

Separate files with parameters

There is no good enough reason to justify storing the settings in the same file as the script. Always create a separate file and include it at the very beginning of the script. You will understand how important this is when you have to edit a bunch of files due to changing one parameter. It’s really quite easy:

include(“config.php”);

Comments are your friends

Of course, if you are in a hurry or typing code on the wave of inspiration, it becomes somehow not up to comments. But code written a long time ago is hard to understand, even if you wrote it. Better help yourself with a couple of comments in key places, then to reduce the time to understand the next script.

// Single line comment

/** Multiline

comment **/

Really, just? You should also pay attention to PHPDoc.

Format your code wisely

There is nothing worse than a huge wall of code, the author of which obviously did not know about the existence of the Tab button. Even comments will not save you – indents were invented in order to logically separate code fragments from each other. And whether or not you use indentation says a lot about you as a programmer. This code is not formatted correctly:

function dothisformula($a,$b) { $c = $b+$a;

    $e=3;

while ($c < 20) {

$e = $e – 1; $c = $c + 1; }

return $e; }

And this is the same code, but with the correct formatting:

function dothisformula($a, $b)

{

    $c = $b + $a;

    $e = 3;

    while ($c < 20) {

        $e = $e – 1;

        $c = $c + 1;

    }

    return $e;

}

If you want to know exactly which way of formatting the code is correct, read the PSRs.

Give variables meaningful names

Of course, it is impossible to come to a consensus on this issue. camelCase or under_score? Do I need Hungarian notation? One thing is important here: once and for all decide what is closer to you. And even if you want to change the style, please don’t do it in the middle of a project! Different naming options for variables in the same project or, even worse, in the same file is terrible. And no magic numbers! Feel free to use constants.

Initialize Variables

Of course, PHP automatically creates variables when you try to access them. But don’t you think that using this feature is rather risky? It is good practice to always initialize variables before first use. This will make your code clearer and help you make sure you don’t accidentally access an uninitialized variable.

$foo = array();

$bar = 0;

$bas = false;

Boolean is false, otherwise true

If you check some condition and then store the result of the comparison in a boolean value, when initializing the variable for the result (we always initialize the variable beforehand, remember?), first set it to false. That is, you don’t have to do this:

function getStatus()

{

    $result = true;

    if ($i != 2)

      $result = false;

    return $result;

}

Better like this:

function getStatus()

{

    $result = false;

    if ($i == 2)

      $result = true;

return $result;

}

Why is this? Imagine that you are validating the data before querying the database. If for some reason the if block is suddenly not executed, then the value of the variable will remain false – this way you will insure yourself against getting into the database of erroneous data. Code sometimes has to deal with sensitive data, so it’s best to first assume that all data is wrong until proven otherwise. This rule is practically written in blood.

By the way, it is better to check whether the data is as we need it, than whether it is as we do not need it.

Use quotes when referring to array elements

In the code of different developers, you can see two options for accessing the elements of an associative array:

$name = $names[‘marc’];

$name = $names[marc];

When executing the second option, PHP will first try to find a constant named marc. And only if there is none, marc will be converted to a string and passed as such. It is better not to think about what could happen if such a constant suddenly exists … Always put quotes so that this does not happen.

Use commas to refer to multiple lines in one call

If you need, for example, to refer to the value of a variable and to a string in one function call, it is better to use commas, not periods. Why? The dot is the string concatenation operator, this operation will be slower. Proof.

Again. So it is necessary:

echo “Hello, my name is “, $name;

And this is how you don’t have to:

echo “Hello, my name is ” . $name;

Use ternary operators

If you have some very simple comparison in your code, it is advisable to use the ternary operator so as not to stretch the simple code over several lines. This is what your simple if might look like:

if ($a == 1)

    $b = 2;

else

    $b = 3;

But you can also write it like this:

$b = ($a == 1) ? 2 : 3;

The generalized ternary operator works like this:

$variable = ($condition) ? true : false;

Use strict comparison to compare against booleans

If you are testing a variable for true or false, use === rather than == which is used in other comparisons. A strict comparison of three equal signs will also compare the types of variables.

Leave a Reply

Your email address will not be published.