Php best practices example

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

PHP best coding practices

License

kenashkov/php-best-coding-practices

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

PHP best coding practices

1. Always when writing new code use strict type comparison ‘===’ or ‘!==’

if ($value === $another_value) <> if ('some_string' === $some_string) <>

Existing code must not be modified from ‘==’ to ‘===’ without proper testing as this will introduce bugs.

This also means using strict comparison in the vairous PHP array functions like:

if (in_array($some_value, $some_array, TRUE)) <>

List of array functions that support the strict parameter:

2. When comparing a value or property to a constant always put the constant first. This will avoid the error of having an assignment instead:

if ($object->object_status = $object::STATUS_ACTIVE) < //BUG — this is assignment > if ($object::OBJECT_ACTIVE = $object->object_status) < //this will trigger an error > //and the correct code is if ($object::STATUS_ACTIVE === $object->object_status)

4. Never put a closing ?> tag in the file.

If there is closing tag and by mistake and there is a space or a tab after it this will trigger odd errors about «headers sent».

5. Always give types to the arguments and return values

Even if the value is mixed provide this in a comment:

function f1( /* mixed */ $arg1) : void <>

Unless the argument can be of any type it is better to provide the expected types in the comment:

function f1( /* int|string|null */ $arg1) : void <>

Soon PHP will support union types and these should be used when available.

6. Always use typed properties

Typed properties are available since PHP 7.4. Whenever possible initialize them:

class c1 < private string $name; private ?int $age = NULL; private string $from_planet = 'Earth'; >

7. Modifying value in a foreach loop

In order to modify the value in the foreach loop the value must be passed by reference:

If after this loop a second loop is added that uses the same variable name for the value but this time without a reference it will overwrite the last element from the previous loop:

foreach ($data as &$record) < $record['some_key'] = 'some_value'; > foreach ($another_data as $record) < $record['some_key'] = 'another_value';//this will actually overwrite the last element from $data >

To avoid this always after the loop unset the variable used for the value and passed by reference.

foreach ($data as &$record) < $record['some_key'] = 'some_value'; > unset($record); //dont do $record = NULL; as this will actually set the last element of $data to NULL foreach ($another_data as $record) < $record['some_key'] = 'another_value';//this will actually overwrite the last element from $data >

OR RECOMMENDED — follow the Basic Coding Standard and prefix all local variables that are references with ‘_’:

foreach ($data as &$_record) < $record['some_key'] = 'some_value'; > //so even if there is a second loop that does not pass by reference then it will use $record, not $_record foreach ($data as $record) < print $record['some_key']; > //and the last element will not be overwritten

This does not require extra code ( unset() ) which can be forgotten.

8. References to array indexes

Whenever are references created to array indexes it must be ensured that these indexes exist. The following code will produce the odd result of creating the index with a NULL value instead of throwing an error about non existing offset:

$arr = []; $a =& $arr[22];//this will not trigger an error - instead will produce $arr[22] = NULL;
if (array_key_exists(22, $arr)) < $a =& $arr[22]; >

9. Always use constants and never hardcoded values:

$role_id = 4; //vs $role_id = Roles::SALES_MANAGEMENT;

Always define constants if there are no already defined ones and name them appropriately.

Never catch \Exception or \Throwable unless you really need that and you know what you are doing. When such an exception is caught a proper logging must be in place (see the «Exceptions handling» section below).

Whenever an exception is caught the catch block must not be empty — it must have either a comment explaining why the block is empty (meaning why this exception is safe to be ignored and not have handling code) or a logger/proper handling code.

The else-if blocks must end with an non empty else. Even if the logic does not require an else-if to have a final else which should contain:

  • remain empty and just have a comment why it is safe to remain empty
  • contain a logger
  • throw a LogicException (for an unexpected value) The same is valid for the switch-case — it must have a default: entry even if such is not required by the application logic.

13. Future proof IF statements

Avoid declaring variables in an IF statement even if in both IF & ELSE the variable is declared.

if ($cond1) < $var1 = 1; > else < $var = 2; >

The above code is not future proof as someone may add an elseif and forget to define the variable.

if ($cond1) < $var1 = 1; > elseif($cond2) < //does something else > else < $var = 2; >
$var = 2;//some default value if ($cond1) < $var1 = 1; >

This way even if someone adds a an else or an elseif the variable will be defined. The code should be always thought of and planned so that there is a default value (this is the value that is set in the else block or in the above case — predefined before the if). If this is not possible and it is preferred to have an undefined variable error than a wrong value then it is acceptable to have the variable defined in each else/if.

The comparison of strings should be always done by converting both of them to lower case (unless the case matters). This is valid even for hardcoded strings (because a hardcoded string like ‘false’ may get converted to ‘FALSE’ during code replace or refactoring be it manual or automatic.

if ( strtolower($node) === strtolower(‘true’) )

If the closure will not need to use $this it should be declared as static one:

$Function = static function() < //do something >;

This is done so that it is avoided having one more reference to $this. Tthis may prevent object destruction based on the scope as this reference may become a circular reference if this closure is assigned to an object property. In this case it will be collected when the GC is triggered instead of the object be collected when the local automatic reference to it is destroyed.

16. Never use global constants

Always use namespaced constants instead of global constants to avoid collisions when multiple libraries are included.

17. Never use global variables

Always avoid using global variables as this may lead to a collision when using multiple pieces of software. Even when just starting your framework like:

//some require()s //some app initialization $App = new My\Framework\App(); $App->initialize(); //other app initialization

Instead use IIFE (Immediately-invoked Function Expression)

(function()< //some require()s //some app initialization $App = new My\Framework\App(); $App->initialize(); >)();
require('app.php'); (new App())->initialize();

But this is not safe if the app.php file contains global variables.

Источник

30+ PHP Best Practices for Beginners

PHP is the most widely used language for server-side programming on the web. Here are 30+ best practices for beginners wanting to gain a firmer grasp of the fundamentals. We have also written posts like these for HTML, CSS, and JavaScript.

1. Befriend the PHP Manual

If you’re new to PHP, then it’s time to get acquainted with the awesomeness that is the PHP manual. The PHP manual is incredibly thorough and has truly helpful comments following each article. Before asking questions or trying to figure out an issue on your own, save some time and just head straight to the manual. Odds are the answer to your question is already nestled in a helpful article at the PHP.net site.

2. Turn on Error Reporting

Error reporting in PHP is very helpful. You’ll find bugs in your code that you might not have spotted earlier, as not all bugs keep the application from working. There are different levels of strictness in the reporting that you can use, but E_ALL will show you the most errors, critical and warnings alike.

Once you’ve gotten your application ready for production, you’ll want to turn off error reporting, or your visitors will see strange errors that they don’t understand.

3. Try an IDE and Feature Rich Editor

The great thing about programming is that you can write your PHP code in Notepad, and it will still run properly on a server if written correctly. However, your productivity will take a hit if you don’t use a full-blown IDE or at least a feature-rich text editor.

IDEs (Integrated Development Environments) are helpful tools when you want great support for a particular language. Different languages come with their own IDEs like PhpStorm for PHP. They give you features like syntax highlighting, code completion, error warnings, and refactoring (reworking).

You can also use some general-purpose text editors for writing code. Visual Studio Code is an excellent example of an editor which offers a lot of great features for multiple languages by integrating with third-party extensions.

Visual Studio Code

4. Try a PHP Framework

You can learn a lot about PHP just by experimenting with PHP frameworks. Frameworks like CakePHP or CodeIgniter allow you to quickly create PHP applications, without having to be an expert with PHP. In a sense, they’re almost like PHP training wheels that show you what a PHP application should look like, and show you valuable programming concepts (like separating the logic from the design).

However, my advice for you would be to first learn the basics of the language and then take a look at some smaller open-source projects to see how they write code and then move on to big projects.

5. Learn the DRY Approach

DRY stands for Don’t Repeat Yourself, and it’s a valuable programming concept, no matter what the language. DRY programming, as the name implies, is ensuring that you don’t write redundant code. Here’s an example from Reinhold Weber:

$mysqli = mysqli_connect('localhost', 'reinhold', 'secret_hash'); 
mysqli_select_db('wordpress') or die("cannot select DB"); 

now with the DRY approach:

$mysqli = mysqli_connect($db_host, $db_user, $db_password); 
mysqli_select_db($db_database); 

You can read more about the DRY programming principle on Artima and Wikipedia.

6. Indent Code and Use White Space for Readability

If you don’t use indentations and white space in your code, the result looks like a Jackson Pollock painting. Ensure that your code is readable and easy to search because you’ll most definitely be making changes in the future. IDEs and advanced text editors can add indentation automatically.

7. «Tier» Your Code

Tiering your applications is nothing more than separating the different components of the code into different parts. This allows you to easily change your code in the future. Envato Tuts+ writer Jason Lengstorf has written an excellent article on how to tier your PHP applications for easier maintenance.

Источник

Читайте также:  METANIT.COM
Оцените статью