You get a bonus - 1 coin for daily activity. Now you have 1 coin

Good PHP habits

Lecture



Like any other programming language, php provides the ability to record the same actions in different ways. One way of recording is more beautiful, the other - not very. For a beginner web developer, it may not be obvious how best to describe an action in PHP, so I’ll demonstrate some of the techniques here.

Passing through arrays / lists

Where possible, we use foreach instead of for ($ i = 0; $ i <$ count; $ i ++) to go through arrays and lists:

  $ arr = array (1, 2, 3, 4);
 foreach ($ arr as $ number) {
   echo $ number;
 }

 $ arr2 = array ('name' => 'John', 'email' => 'jon @ smith');
 foreach ($ arr2 as $ key => $ value) {
   echo "\ n $ key = $ value";
 }

Do not abuse the prefix @

The prefix @ before expression in PHP suppresses the output of warnings, even if the script is actually a logical error, for example, accessing an object as an array:

  $ data = new stdClass ();
 $ data-> x = 1;
 echo @ $ data ['x'];

In this example, the third line will be Fatal error, but you will not see messages about it, so finding such an error in a large project may be difficult. Therefore, use @ only when it’s really necessary .

Variable initialization

Always initialize variables. That is, assign an initial value before reading it from a variable.

The PHP language was born at a time when the programming culture was usually not thought much of, so PHP allows various liberties, such as uninitialized variables. A program that accesses an uninitialized variable will work, but it may hide a hidden defect that the developer does not realize.

Therefore, you must always initialize variables before accessing them:

  $ users = getUsers ();
 $ search = 'Ivan';

 // Poorly:
 foreach ($ users as $ user) {
   if ($ user-> name == $ search) {
     $ found = $ user-> id;
   }
 }
 if ($ found) {
   echo "$ search = $ found";
 }

 // It is better:
 $ found = null;
 foreach ($ users as $ user) {
   if ($ user-> name == $ search) {
     $ found = $ user-> id;
   }
 }
 if ($ found) {
   echo "$ search = $ found";
 }

Access to array elements that may be missing

Reversal to the missing element of the array generates a remark (Notice). To prevent this from happening, we use isset () to check for the presence of an element in an array or a data member in an object. This is preferable to using the @ prefix, since @ does not prevent Notice, but only suppresses the message about it, which leads to wasted computing power.

On the developer's machine, the output of Notice to the page and to the log must be included so that the appeal to non-existent variables does not go unnoticed.

  $ userId = isset ($ _ GET ['userId'])?  $ _GET ['userId']: null;
 if ($ userId) {
   echo 'Hello, user nr.  ', $ userId;
 }

 $ email = isset ($ user-> params-> email)?  $ user-> params-> email: null; 

Repetitions of similar code

Any reps should be avoided. If you look at the program and see several similar lines or blocks, it almost certainly means redundant copying (copy-paste), which is the developer’s worst enemy.

In the example below it is clearly seen that the same piece is repeated 5 times when accessing the parameter list. This piece is rewritten so that there is no repetitive fragment. Now, if you have to change the code, you will need to make changes in only one place.

Even worse than repeating large blocks of code. In this case, in order to remember how they differ from each other, one has to carefully study each of the repetitions in order to “find 10 differences,” and then proceed to change, which, again, will have to be made to each copy of the block. Those who have encountered such recurring fragments, in which it was necessary to make changes, know that this can be a hellish nightmare compared to other problems in the code.

In general, the rule is: no repetitions ! Instead of repeating code, there should be calls to the function or method that implements these actions. Or, as in the simple example below, an additional variable is entered.

  // Poorly:
 if (isset ($ search ['zipcode'])) {
 $ request ['FindArticles'] ['request'] ['search_params'] ['address'] ['zip_code'] = $ search ['zipcode'];
 }
 if (isset ($ search ['zipcodeRadius'])) {
 $ request ['FindArticles'] ['request'] ['search_params'] ['address'] ['radius'] = $ search ['zipcodeRadius'];
 }
 if (isset ($ search ['fuel'])) {
 $ request ['FindArticles'] ['request'] ['search_params'] ['fuel_types'] ['fuel_type_id'] = $ search ['fuel'];
 }
 if (isset ($ search ['minPowerAsArray'])) {
 $ request ['FindArticles'] ['request'] ['search_params'] ['kilowatt'] ['from'] = $ search ['minPowerAsArray'];
 }
 if (isset ($ search ['maxPowerAsArray'])) {
 $ request ['FindArticles'] ['request'] ['search_params'] ['kilowatt'] ['to'] = $ search ['maxPowerAsArray'];
 }

 // It is better:
 $ params = array ();
 if (isset ($ search ['zipcode'])) {
 $ params ['address'] ['zip_code'] = $ search ['zipcode'];
 }
 if (isset ($ search ['zipcodeRadius'])) {
 $ params ['address'] ['radius'] = $ search ['zipcodeRadius'];
 }
 if (isset ($ search ['fuel'])) {
 $ params ['fuel_types'] ['fuel_type_id'] = $ search ['fuel'];
 }
 if (isset ($ search ['minPowerAsArray'])) {
 $ params ['kilowatt'] ['from'] = $ search ['minPowerAsArray'];
 }
 if (isset ($ search ['maxPowerAsArray'])) {
 $ params ['kilowatt'] ['to'] = $ search ['maxPowerAsArray'];
 }
 $ request ['FindArticles'] ['request'] ['search_params'] = $ params;

Comment where appropriate

Commenting on code is actually a good habit. When working in the development team, comments should be provided with all internal APIs that everyone constantly has to use. It is also mandatory to comment on the difficult parts of the code: the implementation of cunning algorithms, and other places where you can not figure out without a half liter.

But to put a comment where everything is obvious - to spend your time , the time of those who will read this code, and disk space. For example, in the example below, the comments are completely useless, since the code is easy to read and speak for itself:

  // Initialization of variables:
 $ totalTeethCount = 0;
 $ totalWeight = 0;
 // Walk through users:
 foreach ($ users as $ user) {
   $ totalTeethCount + = $ user-> teethCount;
   $ totalWeight + = $ user-> weight;
 }

Clear names of variables, functions, methods

You can even achieve good readability of a program by simply choosing the names of variables and functions that speak for themselves. Various unobvious abbreviations in variable names should be avoided, unless there is a specific reason.

Output HTML snippets from PHP

When you need to output an HTML fragment in a PHP script, should this be done not via echo, but in blocks?> .... <? Php. Practice shows that in most cases it is more convenient to work with outputted HTML when it is outside of PHP code (and this is correct, since PHP is one language, HTML is a completely different one). HTML output via echo makes writing long chains from string concatenation through the "." Operator, adding a backslash before quotes. HTML written in this way looks like a mash-up of quotes, in which it is difficult to find and fix the right place.

Compare two code snippets in which the list of objects is displayed in HTML. Which one is clearer? I think the second one.

  // Poorly:
 foreach ($ items as $ item) {
   echo '<tr> <td>'.  $ item-> id.  '</ td> <td> <a href="item/'. $item-> id.' "> '.  $ item-> title.  '</a> </ td> </ tr>';
 }

 // It is better:
 foreach ($ items as $ item) {
   ?>
   <tr>
     <td> <? php echo $ item-> id?> </ td>
     <td> <a href="item/<?php echo $item-> id?> "> <? php echo $ item-> title?> </a> </ td>
   </ tr>
   <? php
 } 

Request Processing and HTML Output

Scripts that issue HTML can simultaneously contain an implementation of the application logic. For example, processing a user request and displaying the result is an HTML page. In such pages, you should clearly separate the reception of input parameters, processing the request and outputting the result , without intermingling the processing and output HTML code between them. In large software projects, as a rule, this division is even stronger: different components or classes (MVC, Model / View / Controller) are responsible for processing and displaying the graphical interface.

In small scripts, there is no point in creating different classes for processing and displaying, but at least visually it is necessary to separate processing and output: at the beginning of the PHP script, input parameters processing, then processing the user's request, then output HTML. These parts can be separated visually with the comments "/////// ....." or whatever you like :).

Closing marker?>

At the end of the PHP file, if it ends with a PHP code, and not HTML, you do not need to put a closing marker? Moreover: the presence of this marker at the very end of the file can, under certain conditions, lead to an error that will be very difficult to detect.

created: 2014-10-16
updated: 2021-03-13
290



Rating 9 of 10. count vote: 2
Are you satisfied?:



Comments


To leave a comment
If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Software and information systems development

Terms: Software and information systems development