With the aim being to instill best practices, I think it would be beneficial to include a common pitfalls or user tips section. However, I would like to gauge others opinions first.
I'm sure everyone will have their own opinions, but I've included a few examples of common issues that I've found in beginners/novice code.
Examples:
Comparison operators:
One common pitfall of beginners is not fully understanding comparison operators, which can lead to misfortune when using strict comparison functions (there are warnings in the docs, but it's often overlooked).
<?php
$a = 5; // 5 as an integer
var_dump($a == 5); // returns true
var_dump($a == '5'); // ignores type and returns true
var_dump($a === 5); // compares type/value (integer vs integer) and returns true
var_dump($a === '5'); // compares type/value (integer vs string) and returns false
/**
* Strict comparisons
*/
$str = strpos('testing', 'test');
var_dump($str); // returns (int) 0
if ($str) // $str (0) is interpreted as false
if ($str !== false) // true, as strict comparison was made
String types:
I propose informing users to the benefits of each and when they should be used... I won't go in depth, but here's a short overview:
- Single quotes aren't parsed (quicker)
- Double quotes can host escaped characters and can evaluate variables
- Heredoc vs Nowdoc (same as single vs double)
<?php
'How are you today?'; // simple string, no need to parse
"I'm $mood today"; // using double quotes avoided escaping and concatenating
Lines should be concatenated when exceeding the soft line limit (80/120 characters):
<?php
'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.';
'Lorem ipsum dolor sit amet, consectetur adipisicing elit,'
. ' sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.';
Unneeded "else":
I often see "else" included in every conditional argument, however in a lot of cases "else" is unneeded:
<?php
function test($a)
{
if ($a) {
return true;
} else {
return false;
}
}
function test($a)
{
if ($a) {
return true;
}
return false;
}
Ternary operators:
I'm a huge fan of ternary operators, but I've come across a few users who've used them in excess causing code to become harder to read.
<?php
// okay
$a = 5;
echo ($a == 5) ? 'yay' : 'nay';
// excessive
$b = 10;
echo ($a) ? ($a == 5) ? 'yay' : 'nay' : ($b == 10) ? 'excessive' : ':(';