October 14th, 2009

21 mistake of programmer PHP

This series of clauses{articles} is intended for those programmers in language PHP which want to avoid most the general{common} mistakes in a spelling of a code. The reader, at least, should know general{common} syntax PHP, and also some experience of use of language in practice is rather desirable.

This series of clauses{articles} is intended for those programmers in language PHP which want to avoid most the general{common} mistakes in a spelling of a code. The reader, at least, should know general{common} syntax PHP, and also some experience of use of language in practice is rather desirable.

Introduction

One of most strengths PHP is, simultaneously, and his{its} weakness: PHP it is very simple in studying. It involves many people; however, despite of his{its} seeming simplicity, not so simply to learn to use this language correctly and effectively.

As a rule, put in insufficient practice of programming. Inexperienced programmers become before the person of necessity of creation of complex{difficult} webs – applications. Therefore mistakes of which would be avoided by the skilled programmer, such as unreasonable use of function printf () or misuse of semantics PHP are pretty often supposed.

In this series from three clauses{articles} characteristic mistakes are submitted most, in our opinion. These mistakes can be classified on several categories, from <noncritical> up to <fatal>. Alongside with the analysis of these mistakes, ways of their avoidance, and also the some people <small cunnings>, saved up for many years of practice of programming are submitted.

Part 1: 7 <children’s> mistakes (¹ 21-15 Are described, upside-down, according to a degree of gravity on our classification). Such mistakes do not cause serious problems, but result in reduction of an overall performance of the program, and also are expressed in bulky trudnochitaemom a code in which, besides, it is difficult to make changes.

Part 2: the Following of 7 mistakes (¹ 14-8) concern to <serious>. They conduct to even more significant reduction of speed of performance of a code, reduction of safety of scripts; the code becomes even more confusing.

Part 3: Descriptions seven, last, <fatal> mistakes. These mistakes are conceptual by the nature and are the reason of occurrence of the mistakes described in 1-st and 2-nd parts of clause{article}. They include also such mistakes, as insufficient the attention, given both to the project as a whole, and to a code of the program, in particular.

21. Unjustified use of function printf ()

Function printf () is intended for a conclusion of the formatted data.

For example, she{it} should be used if necessary a conclusion of a variable in a format from a floating point with the certain accuracy, or in any other case when there is a necessity of change of a format of the deduced{removed} data.

The example of the proved application of function printf () is below resulted. In this case she is used for the formatted conclusion of number <pi>:

<? php

printf (” Number Pi: %2fn <br> n “, M_PI);

printf (” It too number Pi: %3fn <br> n “, M_PI;

printf (” And it Pi: %4fn <br> n “, M_PI);

?>

The note: cases of pathological fear of function printf () when people write the functions of the formatted conclusion, at times till 30-40 lines Are observed, though the unique call of function printf could solve all problems ().

Many programmers use function printf () for a conclusion of variables, results of a call of functions, and sometimes even the usual text data. Most often it occurs in the following two cases:

* When it was necessary to use function print ();

* At a conclusion of the results returned by functions.

When it is necessary to use print ()

The call of function printf () is frequently used there, where it was necessary to use print (). In the following example function printf () is used for a conclusion of four variables:

<? php

$name = ‘ Sterling Hughes’;

$job = ‘ Senior Engineer ‘;

$company = ‘ DesignMultimedia ‘;

$email = ‘ shughes@designmultimedia.com ‘;

printf (” My name is %sn <br> n

I work %s, %sn <br> n

My E-mail address: % sn <br> n “,

$name, $job, $company, $email);

?>

In this case it is possible (and it is desirable!) application print ():

print ” My name is $namen <br> n

I work in $company, $jobn <br> n

My E-mail address: $emailn <br> n “;

Use print () instead of printf () in cases when the unformatted data as in the given example, gives the following benefits are deduced:

* Increase in productivity: Function printf () formats the arguments before a conclusion. Thus, time of its{her} performance is more, than for functions print () or echo ().

* Clearer code: All the same, it is necessary to recognize, that use of function printf () is complicated with reading a code (having sufficient experience of programming on C, it, certainly, concerns to a lesser degree). That function printf () has not led the most unexpected for you in the image, need as knowledge of syntax of the given function, (i.e. %s defines{determines} a line format of a conclusion whereas %d – decimal), and knowledge of types of variables.

Use of function printf () for a conclusion of the value returned by function

One more characteristic mistake of use of function printf () – a conclusion of the value returned by function, as in the following example:

<? php

printf (” It is found %d ocurrences of a line %s “, count ($result), $search_term);

?>

Alongside with function print (), at its{her} use in the same purposes, it is necessary to use the operator ‘. ‘ In this case this operator adds the text to result of a call of function:

<? php

print “is found”.

count ($result).

” Ocurrences of a line $search_term “;

?>

Use of the operator. In pair with function print () allows to avoid use of slower function printf ().

20. Incorrect application of semantics of language

Many programmers use in job PHP, actually not understanding subtleties of this language. One of subtleties – a difference between syntax and semantics PHP.

* Syntax PHP:Predstavljaet itself corrected a set for definition of elements of language. For example, how we determine a variable? We put a sign $ before its{her} name. How we determine function? Generally, using brackets, arguments, etc.

* Semantics PHP: Represents a set corrected for application of syntax. For example, we shall take function with two arguments that is defined{determined} by its{her} syntax. And as arguments she should be passed variables of line type? Is it is defined{determined} by semantics.

Notice: <follows>. In languages with clear split of types (such as Java or C) no concept <follows> (generally though there are also exceptions). In that case the compiler will compel to use variables of strictly certain type.

Languages in which there is no definition of types of variables, give more flexibility in a spelling of a code. But, anyway, in case of misuse of semantics for the majority of functions PHP it is necessary to expect occurrence of the message on a mistake.

Let’s take a piece of a code which opens a file and deduces it{him} postrochno:

<? php

$fp = @fopen (‘ somefile.txt ‘,’ r ‘)

or die (‘ I can not open a file somefile.txt ‘);

while ($line = @fgets (“$fp”, 1024)) // Here a mistake!

{

print $line;

}

@fclose (“$fp”) // Here again too color

or die (‘ I can not close a file somefile.txt ‘);

?>

In this case the message on a mistake of type will appear:

” Warning: Supplied argument is not a valid File-Handle resource in tst.php on line 4 ”

(” Attention: the argument cannot be a descriptor of a file “)

It is called by that, that the variable $fp is made in double inverted commas, that unequivocally defines{determines} her{it} as a line, whereas function fopen () expects as the first argument a descriptor, but not a line. Accordingly, you should use a variable which can contain a descriptor.

The note: In this case, the line type is allowable sintaksicheski.

For the decision of a problem it is necessary to clean{remove} double inverted commas simply:

<? php

$fp = @fopen (‘ somefile.txt ‘,’ r ‘)

or die (‘ I can not open a file somefile.txt ‘);

while ($line = @fgets ($fp, 1024))

{

print $line;

}

@fclose ($fp)

or die (‘ I can not close a file somefile.txt ‘);

?>

How to avoid the wrong application of semantics?

In the resulted example the message on a mistake is generated. But PHP gives the programmer of more freedom, than other, traditional programming languages. It allows to receive interesting results. At least, it is theoretically possible to write a correct code, incorrectly using semantics of language.

But be cautious, making advances to semantics of language! Occurrence of hardly perceptible mistakes in programs is possible. If all of you-taki have decided to experiment, you should understand three key moments:

* Types: In PHP each variable at any moment concerns to the certain type. And despite of that fact, that its{her} type it is possible to change it freely. In other words, in language PHP the variable cannot exist, thus not concerning to the certain type (and, accordingly, not possessing the characteristics, inherent in this type). In PHP there are 7 basic types of variables: Boolean, resource, integer, double, string, array and object.

* Area of visibility: In PHP variables have area of visibility which defines{determines} that, whence she can be accessible, and as far as will exist for a long time. Nedoponimanie concepts <areas of visibility> it can be shown as a various sort of <floating> mistakes.

* php.ini: At a spelling of a code it is necessary to understand, what not all users have the same configuration of hardware-software means, as well as you. Thus, it is completely necessary to be convinced once again, whether serviceability of your code in that configuration in which the program should work is saved, instead of in in what it was developed.

19. There is not enough or too much kommentirovannyj the text

Badly documentary text of the program is an attribute ehgoistichnogo the programmer. Result of attempt of the analysis of your program with the purpose of entering improvements will be only a headache. And all programmers count the self-documentary code a good form, but extremely seldom write comments.

It is necessary to avoid superfluous comments also. It too meets very seldom, and, besides, creates difficultly readable initial code. The following example illustrates it:

<? php // the Beginning of a code

$age = 18; // the Age is equal 18

$age ++; // we Shall increase $age by one year

// We shall print a greeting

print ” to you now 19 years, and it means, that to you already was: “;

print ” n <br> n <br> n “;

// A cycle ‘ for ‘ to deduce{remove} all

// The previous values of age

for ($idx = 0; $idx <$age; $idx ++)

{

// We shall print each value of age

print ” $idx letn <br> n “;

}

// The end of a code

?>

And nevertheless: where a golden mean?

So, what volume of comments should be placed in a script?! It depends on much: from time which you have, from politics of the company, complexity of the project, etc. Nevertheless, remember some main principles which should be followed at a spelling of programs without dependence from your decision:

* Before a body of function always place the comment – purpose{appointment} of function.

* Add comments in doubtful sites of a code, when there is no confidence, that he will work as it is necessary.

* If purpose{appointment} of a code unevidently, bring in the information on applicability of this site. You then will use this comment.

* Avoid comments of a kind * – use only/* */or //.

The following example illustrates good style of comments:

<? php

// Random_Numbers.lib

// Generation of random numbers of various type

mt_srand ((double) microtime () *1000000);

//

// mixed random_element (array $elements [, array weights])

// Returns a stochastic element of file – argument

// The file weights contains relative probabilities

// Samples of elements

//

function random_element ($elements, $weights = array ())

{

// For correct functioning this algorithm

// The quantity{amount} of elements of a file should be equal

// To quantity{amount} of elements of a file of relative probabilities

if (count ($weights) == count ($elements)) {

foreach ($elements as $element) {

foreach ($weights as $idx) {

// The note: we do not use $idx, because

// Access to separate elements is not necessary for us

// A file weights

$randomAr [] = $element;

}

}

}

else {

$randomAr = $elements;

}

$random_element = mt_rand (0, count ($randomAr) – 1);

return $randomAr [$random_element];

}

?>

18. It is too much variables – too big execution time

The some people directly suffer obsession to enter time variables where it is necessary and where it is not necessary. It is completely impossible to understand, than the person written such code was guided:

<? php

$tmp = date (” F d, h:i a “); // i.e. a format of date February 23, 2:30 pm

print $tmp;

?>

For what the time variable here is used?! She simply is not necessary:

<? php

print date (” F d, h:i a “);

?>

Unfortunately, many programmers cannot get rid of this bad habit in any way. Use of time variables slows down performance of the program. For increase in speed of a code where it is possible, it is better to use an investment of functions. Use of time variables frequently increase execution time of scripts almost by a quarter.

One more reason on which it is necessary to avoid use of excessive quantity{amount} of time variables, this deterioration of readership of a code. Compare two resulted examples. What from them looks more elegantly – with use of a time variable or without? What code is easier for reading? Use of superfluous time variables conducts to a spelling of less readable and clear code.

Pluss of use of time variables

Introduction of time variables allows to simplify some complex{difficult} expressions or calls of functions. Still they benefit, when allow to avoid a repeated call of function with the same arguments.

Example in which it is not used superfluous variables:

<? php

// string reverse_characters (string str)

// Overturns a line of symbols

function reverse_characters ($str)

{

return implode (” “, array_reverse (preg_split (“//”, $str)));

}

?>

To call of function implode () as one of parameters it is passed the result of performance of the enclosed functions, therefore such code is difficult for reading. In this case to us can use of a time variable is healthy to help:

<? php

// string reverse_characters (string str)

// Overturns a line of symbols

function reverse_characters ($str)

{

$characters = preg_split (“//”, $str);

$characters = array_reverse ($characters);

return implode (” “, $characters);

}

?>

Gold rule

If you think, to enter whether or not one more time variable, set to yourself two questions:

* Whether this variable will be used even twice?

* Whether readership of a code will considerably improve with its{her} introduction?

If you have answered any of these questions <yes> then enter a time variable. Otherwise combine calls of functions (if it is necessary) and do without its{her} use.

17. We copy standard functions

Someone recommends to rename standard functions that on Visual Basic’? it was easier to programmers to proceed{pass} to use of language PHP:

<? php

function len ($str) {

return strlen ($str);

}

?>

There are also recommendations, starting programming on PHP, first of all to replace names of the built – in functions with more habitual.

There are, at least, two reasons of it to not do{make}. First and first of all, we receive less readable code. People reading your code, will see weight of obviously unnecessary functions and will be strongly surprised, why you did not use standard functions PHP.

Well and, at last, it slows down the program. Business not only in necessity of processing of great volume of a code, but also that for a call of such user function, is required to more time, than for a direct call of standard function.

Use standard functions of language!

Sometimes so it is difficult to resist{stand}! In fact the programmer seldom knows at once all set of functions – he{it} usually does not have time to remember them all. Why simply to not rename function? But, we shall be repeated, it is not necessary to do{make} it by virtue of the reasons stated above.

Well to have near at hand the directory on functions PHP (it is convenient to use the indexed version in format PDF). And before writing any function, closely{attentively} to see – whether there is she already in the list of standard functions.

But it is necessary to notice, that in codes of programs it is possible to meet the user functions written still{even} before their introduction as standard (for example, functions of comparison of two files). It does not mean, that you necessarily should copy a code and replace with their standard functions.

16. The client part of the program is not separated from a server part

Many programmers recommend to unite code HTML (interpretive on the party{side} of the client) and code PHP (carried out by the server) in one big file.

For small sites it, probably, not bad. But, when your site will start to grow, you can face problems if necessary to add any new functions. Such style of programming results in very <disobedient> and bulky code.

Comments are closed.

footer

Design & programming by: Web Development Company CONKURENT LLC 2003-2009.