Skip to content

Instantly share code, notes, and snippets.

@lepfsd
Created August 11, 2017 05:10
Show Gist options
  • Save lepfsd/28f09662c1dcc431fe20c33a3deff36f to your computer and use it in GitHub Desktop.
Save lepfsd/28f09662c1dcc431fe20c33a3deff36f to your computer and use it in GitHub Desktop.
20 Tips you need to learn to become a better PHP Programmer
//Use <?php and ?>
<? ... ?> // Incorrect
<?php ... ?> // Correct
<?=$Var?> // Incorrect
<?php echo $Var ?> // Correct
//Separate Configuration Files
include("<span class="skimlinks-unlinked">config.php</span>");
// code goes here ...
//Comments are your Friend
//Use Indentation and Spacing
There’s nothing much worse than having to modify somebody’s code and realizing nothing has been indented properly. Having well indented code with the right spacing immediately says a lot about you as a programmer. Ideally, you should be able to immediately figure out whether a loop has ended or not by just quickly looking through your code. Here’s an example of badly indented code:
function dothisformula($a,$b) { $c = $b+$a;
$e=3;
while ($c < 20) {
$e = $e - 1; $c = $c + 1; }
return $e; }
And here’s the same code, properly formatted:
function dothisformula($a, $b) {
$c = $b + $a;
$e = 3;
while ($c < 20) {
$e = $e - 1;
$c = $c + 1;
}
return $e;
}
//Give your Variables Meaningful Names
Always give your variables name that mean something to you. Take this one step further by also including some details about what type of data they store. For instance, if we were using a variable as an integer, you could add an i to the beginning of the name. This especially important since we do not specify a type when declaring a variable in PHP.
Choosing whether to have caps or not in your variable name is up to you but it is often recommended to capitalize the first letter of every word in your variable. This makes it easy to read and understand.
Here’s what I use:
$iNumber = 10; // For Integers
$sName = "Marc"; // For Strings
$fPi = 3.14159265; // For Floats
$aNames = array(); // For Arrays
$oUser = new User(); // For Objects
$bIsMember = false;
//Initialize your Variables
$aArray = array();
$iInteger = 0;
$bBoolean = false;
//Boolean is False, unless True
If you’re checking whether something is a specific value and storing the result in a boolean value, always start off assuming it’s false. For instance, the following code should be avoided:
function getStatus() {
$bReturn = true;
if ($i != 2) $bReturn = false;
return $bReturn;
}
Instead, you should use:
function getStatus() {
$bReturn = false;
if ($i == 2) $bReturn = true;
return $bReturn;
}
The second is the ideal solution for when you’re just checking one item. Why? Well, imagine you’re validating some data for a database – If, for whatever reason, your if statement is completely missed, your return value will still be false, therefore avoiding the input of invalid data. Since we frequently deal with sensitive data in PHP scripts, it’s better assuming something should not run until proven otherwise, rather than the other way round. I learned this the hard way.
Ideally, your validation should check what your data should be like, not what it shouldn’t be like.
//Using Quotes when accessing Array Keys
When accessing arrays, you might find that the following two lines both work:
$sName = $aNames['marc'];
$sName = $aNames[marc];
In the second line, PHP is actually first trying to find a constant called “marc” and then converting “marc” to a string once no constant is found. Even though it works, you should avoid using no quotes as if you ever create a constant with the same name, your script would stop working.
//Use commas to echo different strings
If you want to output both text and variables in the same string, you can use commas instead of dots. Why? Because it is marginally faster (based on this test).
echo "Hello, my name is ", $sName;
Instead of…
echo "Hello, my name is " . $sName;
//Use Ternary Operators
If you have a simple IF statement, you can use a ternary operator which allows you to do the same thing in one line. Here’s an IF statement:
if ($a == 1) $b = 2;
else $b = 3;
You can do the same thing using a ternary operator as shown below:
$b = ($a == 1) ? 2 : 3;
Easy, right? The ternary operation is basically doing this:
$variable = (CONDITION) ? IFTRUE : IFFALSE;
//Use === for Boolean Checks
If you’re checking whether a variable is true or false, use === rather than the usual == which we use for comparisons. The three equal signs tell PHP to also check the variable type.
if ($bIsMember == true) { ... } // Incorrect
if ($bIsMember === true) { ... } // Correct
//Use ++ and — Operators
If you want to increase or decrease an integer by 1, you can easily use incrementing and decrementing operators. If you have the following code:
$iNumber = $iNumber + 1;
$iNumber2 = $iNumber2 - 1;
This should be converted to:
$iNumber++;
$iNumber2--;
The great thing about these operators is the way you can use them while completing other actions (for instance, in an if or while statement). Depending on whether you put the – or ++ before the variable or after, the operator will run before or after the action is complete. The examples below are all valid uses and will help you understand what I mean:
$iNumber = 10;
while ($iNumber++ == 10) { ... }
// This will run once as the increment operator
// is run after the comparison
$iNumber = 10;
if (--$iNumber == 10) { ... }
// This will not run as the decrement operator
// is run before the comparison
$iNumber = 10;
$iTotal = $iNumber++;
// $iTotal will be 10.
$iNumber = 10;
$iTotal = --$iNumber;
//Use Assignment Operators
If you wanted to increase or decrease a variable by more than one, you can easily use assignment operators. Here’s how your code might look:
$a = $a + $b;
$a = $a * 5;
$a = $a - $d;
$a = $a / 3;
Using assignment operators, you can instead write:
$a += $b;
$a *= 5;
$a -= $d;
$a /= 3;
You can also use this for strings. The following two lines do the same thing:
$sString = $sString . "hello";
$sString .= "hello";
//Create a Variable Dump Function
We’re all familiar with print_r which we constantly use as we’re testing our script and figuring out what value our variables currently have. To make this even simpler, you can create a function such as:
function p($var) {
echo "<pre>";
print_r($var);
echo "</pre>";
}
//Use Constants
If you have a variable which never changes, there’s no point constantly re-writing the same thing over and over again. Use constants to define data which you access often like directory paths, error messages etc. I’d recommended giving your constants names which are fully capitalized to help you realize immediately when you’re using them.
define ("DIRECTORY","/path/to/site/");
echo DIRECTORY;
//Use $_GET and $_POST
Avoid using $_REQUEST which gets both POST and GET variables. Use $_GET to get parameters from your URL and use $_POST to get variables submitted from a form:
$sAction = $_GET['actions'];
$sName = $_POST['name'];
//Use Objects instead of Functions
If you function has lots of parameters, it’s time to move over to objects. I’ve worked on projects that got too complex to maintain after a few of the functions ended up having over 20 parameters! The moment you realize you need to modify the way the function is called, you will need to change each and every function call. So, instead of this:
function getProducts($iParameter1, $iParameter2,
$iParameter3, $iParameter4, $iParameter5,
$iParameter6, $iParameter7, $iParameter8,
$iParameter9) { ... }
You can use:
$oProducts->setParameter1(...);
$oProducts->setParameter3(...);
$oProducts->setParameter5(...);
$oProducts->setParameter6(...);
$oProducts->getProducts();
//Use Method Chaining
If you’re doing multiple object method calls that set variables instead your object, you can use method chaining to make your code simpler. To do this, just end each method with return $this; as shown below:
class User {
function setThis($iVar) {
....
return $this;
}
function setThis2($iVar2) {
....
return $this;
}
}
You will then be able to do method chaining:
$oUser = new User();
$oUser->setThis(...)
->setThis2();
//Stop Repeating Code
Don’t repeat any code – If you have a few lines that do the exact same thing, turn them into one function. Or better yet, turn them into an object. Although this might seem like extra work, it will pay off once your application gets bigger and bigger. As a simple example, if you had:
$a = 1;
while ($a < 10) {
$b = $a * 10;
$c = $b * 2;
$d = $c * $b;
echo $d;
$a++;
}
You could write this like this:
function multiply($iVar, $iVar2) {
return ($iVar*$iVar2);
}
$a = 1;
while ($a < 10) {
$b = multiply($a, 10);
$c = multiply($b, 2);
$d = multiply($c, $b);
echo $d;
$a++;
}
Aim for Loose Coupling, Strong Cohesion
Coupling is the degree in which the change in one component requires a change in another. In other words, if you change one function, will you need to change another? The looser the coupling, the more you will be able to modify components without affecting others. Cohesion, on the other hand, is the degree in which different parts form a meaningful unit. Does your main function do practically everything or do you have many functions which each do very specific jobs? If you do, then you have a strong cohesion. Strong Cohesion happens when your components have clearly defined responsibilities and call other functions for processing which does not form part of their objective.
As a PHP Programmer, you should always aim to create components (functions, classes…) that are both loosely coupled and have a strong cohesion to increase code maintainability and extensibility. Whenever creating a function, try to keep in mind that you might have to use it in other scenarios. Avoid adding code which is highly dependent on other components being set up correctly. Ideally, you should be able to change a system and any other systems depending on it will continue to work without modification.
If we apply this to code, here’s a simple example:
1
2
3
4
5
6
7
8
9
10
11
12
13
// We want to add two numbers
// only if the first number is
// lower than 5
function add($iVar, $iVar2) {
if ($iVar < 5) return false;
else $iResult = $iVar+$iVar2;
echo "The Result is ", $iResult;
}
$iVar = 3;
$iVar2 = 2;
add($iVar, $iVar2);
The example above is tightly coupled and has weak cohesion since we are doing validation inside the function itself. We are also putting the result output inside the function itself which will be a problem once we have many functions doing the same and we decide to change the text for it.
Here’s a much better version:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// We want to add two numbers
// only if the first number is
// lower than 5
function add($iVar, $iVar2) {
return $iVar + $iVar2;
}
function result($sMessage) {
return "The Result is " . $sMessage;
}
$iVar = 3;
$iVar2 = 2;
if ($iVar < 5) {
echo result(add($iVar, $iVar2));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment