PHP BEST PRACTICES GUIDE

PHP is a server-side scripting language designed for web development but also used as a general-purpose programming language. As of January 2013, PHP was installed on more than 240 million websites (39% of those sampled) and 2.1 million web servers. (Wikipedia)

I present this guide with fourteen tips and the PHP best practices, so that your PHP code is as effective as possible:

1. Enable error reporting

Use error_reporting(E_ALL) [link] use it along with ini_set (‘display_errors’, ‘On’) [link] . Use them not only for PHP errors, but also to see all compiler warnings PHP, what methods are deprecated, nonexistent indexes, etc.

2. Do not use short tags

To run the PHP code, it hast to be delimited by <?php ?>. We can configure our PHP (php.ini) to use short tags <? ?> , and the script will run exactly the same. But what happens if we change to another server that are not enabled? Our pages will not work as expected any more, and, what is worse, our source code might be printed on screen as plain text, which could be a major security problem.

3. Comparison operators: === vs ==

The operator == compares the value while === compares the value and type.
Since PHP variables do not have an assigned type and it can be changed “on the fly” at runtime, we should be careful when using each operator.

For example, there are functions that return an integer. As the logical value of any integer is true, except for the zero, which is false, we must take this into account when assessing our conditions. The function strpos() searches the position of the first occurrence of a substring within another:

<?php
$str = ‘Zaragoza';

$seek = ‘r'; // Present in $str
$pos = strpos($seek, $str); // $pos = 3

$seek = ‘w'; // Absent in $str
$pos = strpos($seek, $str); // $pos = false

$seek = ‘Z'; // Present in $ str
$pos = strpos($seek, $str); // $pos = 0

?>

Therefore, if we want to verify the presence or not of a string strpos() should not be compared by value (==) but by type and value (===).

4. echo vs print

These functions perform the same task. However, echo is considerably faster than print.

5. Concatenating strings, single quotes (‘) vs double quotes (“)

When working with strings, always avoid using double quotes. PHP analyzes the content of double quotes looking for variables, resulting in a longer run.

6. Search case non-sensitive strings and patterns

The search for a string case non-sensitive stripos() is between 400% and 600% slower than its equivalent case sensitive,strpos(). As for regular expressions, sensitive searches, preg_match(“/ $pattern /”, $string) are, as a rule, slightly more efficient than the equivalent non-sensitive: preg_match(“/ $pattern / i”, $string ).

7. Name conventions

Class name in MixedCase. Eg. ClassName
Methods name in camelCase. Eg. methodName()
Constants in ALL_CAPS. Eg. MAIN_COLOUR
Variables, properties and parameters in camelCase. Eg. $variableInformation
Non-public method and variables in underscore-prefixed camelCase. Eg: $_privateVar

8. Creating Reusable Modules

Code reuse aims to save time and resources and reduce redundancy by taking advantage of assets that have already been created in some form within the software product development process. The key idea in reuse is that parts of a computer program written at one time can be or should be used in the construction of other programs written at a later time.

Avoid having files with hundreds or thousands of lines. Combine the functions that you use frequently in separate Classes/Files and include them.

Eg.

file1.php

<?php
namespace JokiLib;
class Util_Date{

public static function timestampToEnglishFormat($date, $dateSeparator, $timeSeparator = ‘ at ‘){
if ($date == ”) return null;
$temp = explode(‘ ‘, $date);
if (sizeof($temp) != 2) return null;
$dates = explode(‘-‘, $temp[0]);
return $dates[2] . $dateSeparator . $dates[1]. $dateSeparator . $dates[0] . $timeSeparator . $temp[1];
}
}
?>

So, if you want to convert a date to timestamp format to a format with which we are most familiar, we just do
<?php include file1.php; ?>
<?php echo \JokiLib\Util_Date::timestampToEnglishFormat ($myDate, ‘/’); ?>

9. When iterating arrays, sets the maximum value out of the loop

Each call to count() increases up to 50% of the runtime, depending on the size of the array. Then:

// WRONG
for ($ i = 0; $ i <count ($ myArray); $ i ++) {

}
// OK
$ limit = count ($ myArray);
for ($ i = 0; $ i <$ limit; $ i ++) {

}

10. Use the output buffer

Instead of using echo ‘text’ use ob_start() to start storing the text in the output buffer. To complete the capture, you can useob_get_contents() and ob_get_clean() , or ob_end_clean(). [link]

11. Including code

Always use include or require instead of include_once or require_once for a better code caching. [link]

12. Character encoding

Use UTF-8 (without BOM) instead of ANSI. What in ANSI can be a particular character (a Spanish “?” for example), in other coding can be something else entirely. If your website is available in more than one language, it is essential that your encoding is UTF-8 (including encoding and collation of the database). [link]

[update] Use Multibyte String (mbstring) functions instead of standard string functions when working with Chinese / Japanese / Korean characters. [link]

13. Use isset()

isset() is not a function but a language construct. This means that PHP will not have to make any previous operation or be overloaded. [link]

For example, if we need to check if a string has a given length we could use strlen().

Since strlen is a function, PHP needs to perform a previous work to execute the call (convert to lowercase and search the hash table functions), and then perform the function itself.

But we could use isset(), and PHP will not have to make any previous operation or be overloaded.

14. Increase or Decrease variables (++$i vs $i++)

Pre-increase (++$i) is around 10% faster than post-increase ($i++). The reason is that when doing post-increment, PHP needs to create a temporary variable to store the value to be increased

Youssef Jad

Backend Tech Lead | Software Engineer @ Inovola & ZID

9 年

Thanks <3

Shreif ElAgami

Experienced PHP Developer | Expert in Laravel, DevOps, & Scalable Web Applications | Skilled in CI/CD, API Integration, AI-Powered Solutions, & Performance Optimization | Open-Source Contributor

9 年

Very helpful thanks a lot, great work, waiting for more ;)

要查看或添加评论,请登录

社区洞察

其他会员也浏览了