Loading ...
Sorry, an error occurred while loading the content.

7 Common Mistake while coding in PHP

Expand Messages
  • Day Dreamer
    21. Improper use of printf The printf() function is intended for printing formatted data. It should be used, for example, when you need to print out a double
    Message 1 of 1 , Oct 31, 2004
    • 0 Attachment
      21. Improper use of printf

      The printf() function is intended for printing formatted data.
      It should be used, for example, when you need to print out a double
      with two-digit precision, or any other case where you might need to
      change the format of your output before displaying it.
      In the example below, the correct usage of printf()is presented. The
      function is used to format the value of M_PI (Õ) to the desired precision:
      <?php
      /*
      * The three faces of Π
      */

      printf ("Pi is: %.2f\n<br>\n", M_PI);
      printf ("Pi is also: %.3f\n<br>\n", M_PI);
      printf ("Pi is also: %.4f\n<br>\n", M_PI);
      ?>

      Note: I've seen cases where people have had printf()-phobia, writing
      custom functions to format output, sometimes as long as 30-40 lines,
      when a single call to printf() would have done all of the formatting
      for them.
      Many programmers misuse the printf() function by using it to display
      variables, function call results, or sometimes just plain data. Misuse
      of the printf() most often takes place under one of the following
      scenarios:
      • When the print() statement is more appropriate.
      • When displaying the output of a function call.
      When print()Is More Appropriate
      Programmers often use the printf() function where the print()
      statement would suffice. In the following example, printf() is used to
      print out four variables:
      <?php
      $name = 'Sterling Hughes';
      $job = 'Senior Engineer';
      $company = 'DesignMultimedia';
      $email = 'shughes@...';


      printf ("My name is: %s\n<br>\n
      My Job is: %s, %s\n<br>\n
      My E-mail is: %s\n<br>\n",
      $name, $job, $company, $email);
      ?>
      The print() function could have been used in place of printf()as follows:
      print "My Name is: $name\n<br>\n
      My Job is: $job, $company\n<br>\n
      My E-mail is: $email\n<br>\n";
      Using print() instead of printf() when you don't need to print
      formatted data, as in the above example, provides the following benefits:
      • Faster Performance: The printf() function formats your output before
      it displays your text. Therefore, it will take longer to execute than
      a print() or echo() statement.
      • Cleaner code: Let's face it, using the printf() function is a little
      messy for people to read (unless of course they have a C background).
      It requires knowledge of printf() syntax, (i.e. %s denotes a string
      whereas %d represents a decimal) as well as knowledge of types so that
      printf() doesn't mess up your results.
      Using printf() to output the value of a function call.
      Another common error is using printf() to output function call values,
      such as the count function shown in the example below:
      <?php
      printf ("%d occurrences of %s found.",
      count($result), $search_term);
      ?>
      When outputting function call values, the . operator should be used in
      conjunction with print(), as shown in the example below:
      <?php

      print count($result) .
      " occurrences of $search_term found.";
      ?>
      The . operator appends the results of your function call to the text
      you want to display. Using the . operator saves you from using
      printf(), which is slower. The reason being that it tries to format
      your output before it is displayed to the screen.

      20. Misapplying Semantics

      Many programmers use PHP without really understanding the finer points
      of the language. One fine point is the difference between PHP syntax
      and PHP semantics.
      • PHP Syntax: Represents the body of rules for defining a PHP element.
      For example, how do you define a variable? Place a $ in front of the
      word; How do you define a function? Generally speaking, use brackets
      and arguments etc....
      • PHP Semantics: Represents the body of rules for applying the syntax.
      For example, take a PHP function that requires 2 arguments as defined
      by its syntax. Both arguments, however, should be strings – this is
      semantics.
      Notice how we say "should". For strictly-typed languages such as Java
      or C there is not really such a thing as "should" (with exceptions). A
      compiler will force you to use a type in a prescribed, exact manner.
      In loosely-typed languages such as PHP, however, you have more
      flexibility over how you formulate a code statement.
      For most defined PHP functions, however, you should expect an error
      statement if you deviate from the prescribed semantics.
      Consider the following example of opening a file and printing out all
      of its lines:
      <?php
      $fp = @fopen ('somefile.txt', 'r')
      or die ('Cannot open somefile.txt');

      while ($line = @fgets ("$fp", 1024)) // error
      {
      print $line;
      }

      @fclose ("$fp") // error
      or die ('Cannot close somefile.txt');
      ?>
      The example above would generate an error message such as:
      "Warning: Supplied argument is not a valid File-Handle resource in
      C:\Inetpub\wwwroot\tst.php on line 4."
      This is because the $fp variable was passed in double quotes, thereby
      making it a string. However, the fopen() function expects a resource
      identifier as its first argument, and not a string. You would need to
      maintain this argument as a resource identifier.
      Note: The string, however, was correctly typed in syntactically.
      To correct the problem you would simply eliminate the double quotes a
      follows:
      <?php

      $fp = @fopen ('somefile.txt', 'r')
      or die ('Cannot open somefile.txt');

      while ($line = @fgets ($fp, 1024))
      {
      print $line;
      }

      @fclose ($fp)
      or die ('Cannot close somefile.txt');
      ?>
      But could you get away with misapplying semantics?
      Our example above generated an error statement. But PHP enables you to
      customize your scripts to fit a unique scenario or output requirement.
      So, it is at least theoretically possible to "get away" with
      misapplying a semantic.
      Therefore, be aware of the possible outcomes if you decide to play
      with PHP semantics. Misapplying semantics can generate subtle errors
      if you're not paying attention.
      If you would like to customize your scripts you should be sure to
      understand the following key topics:
      • Types: In PHP, every variable will have a defined type at any point
      in time. This is despite the fact that its type can be freely
      converted. In other words, a PHP variable will not exist without
      having some defined type (along with that type's characteristics). PHP
      contains 7 fundamental types: Boolean, resource, integer, double,
      string, array and object.
      • Scope: In PHP, variables have a scope. A variable's scope determines
      where the variable can be accessed and for how long it will exist.
      Misunderstanding the concept of "scope", then, can lead to both subtle
      bugs and major errors.
      • php.ini: When writing scripts that need to be portable it is
      important to understand that not all users will have the same
      configuration that you do. Therefore it is necessary that you add
      checks in your code to ensure that your code runs with the user's
      current configuration.

      19. Lack of Inline Documentation

      Poorly documented source code is, in my opinion, the root of all
      selfish programming. It can lead to incorrect fixes, misconstrued
      meanings and leave people who are reading your code with ear splitting
      headaches. In general, inline documentation is universally agreed to
      as being a good thing, but rarely is it present.
      There is also such a thing as too much documentation. While rare, it
      is also a problem because it leads to overly cluttered source code.
      The following is an example of applying too much documentation:
      <?php // Start off PHP code
      $age = 18; // assign 18 to age
      $age++; // increment $age by one

      // print out introductory text
      print "You are now 19, which means you have been:";
      print "\n<br>\n<br>\n";

      // A for loop to print out all of the
      // previous ages
      for ($idx = 0; $idx < $age; $idx++)
      {
      // Print out an individual age
      print "$idx years old\n<br>\n";
      }
      // End the PHP code
      ?>
      How much documentation?
      To what extent, then, should documentation be added to your script? It
      can depend on any number of things such as your budget, company
      policy, or a script's complexity, etc... There are, however, a few
      guidelines that you can follow regardless of how you decide to
      document your code:
      • Always put a short description of the purpose of a function above
      the function itself.
      • Add comments where things are hacks, or might appear to be wrong but
      that are in fact correct.
      • If a piece of code seems confusing, add a little note about its
      purpose in your script. You'll be thankful for that note later.
      • Use a consistent style of commenting, either /* */ style comments or
      the // style comments (avoid # style comments).
      The following is a brief example of a good commenting style for your code:
      <?php
      // Random_Numbers.lib
      // Generate different types of random numbers.

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

      //
      // mixed random_element(array elements[, array weights])
      // Extract a random element from elements. Weights is
      // the relative probability that each element will be
      // selected.
      //

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

      // There must be exactly the same amount of elements as
      // there are weights for this algorithm to work properly

      if (count ($weights) == count ($elements)) {
      foreach ($elements as $element)
      {
      foreach ($weights as $idx)
      {
      // Note: we don't use $idx, since we
      // don't want to override elements.
      $randomAr[] = $element;
      }
      }
      } else {
      $randomAr = $elements;
      }

      $random_element = mt_rand (0, count ($randomAr)-1);
      return $randomAr[ $random_element ];
      }
      ?>

      18. Too many variables, too much time

      Some people have this utter obsession with temporary variables. I just
      can't seem to understand it whenever I see something like:
      <?php
      $tmp = date ("F d, h:i a"); /* ie January 3, 2:30 pm */
      print $tmp;
      ?>
      Why the temporary variable? It is simply not necessary:
      <?php
      print date ("F d, h:i a");
      ?>
      Unfortunately, it seems that many users have difficulty breaking out
      of this bad habit. Temporary variables slow down the execution time of
      your program. It's faster to omit them altogether and bundle the
      function calls together. Users who use temporary variables often add
      on 25% to the execution time of their scripts.
      Another reason for avoiding too many temporary variables is because
      they just don't look elegant. From our example above, which is more
      concise, the one with the temporary variable or the one without? Which
      one is easier on the eyes? Using too many temporary variables can lead
      to less readable and less concise code.
      Beneficial Uses of Extra Variables
      Temporary variables are useful for replacing long-winded functions or
      expressions. They can serve as an alias of sorts. This is especially
      true when you need to apply the function or expression a number of times.
      Consider the following example, which does not use any more variables
      then necessary:
      <?php

      // string reverse_characters(string str)
      // Reverse all of the characters in a string.
      function reverse_characters ($str)
      {
      return implode ("", array_reverse (preg_split("//", $str)));
      }

      ?>
      The implode function's content is long-winded and thereby difficult to
      read. The use of one or more temporary variables will definitely help
      us out:
      <?php

      // string reverse_characters(string str)
      // Reverse all of the characters in a string.
      function reverse_characters ($str)
      {
      $characters = preg_split ("//", $str);
      $characters = array_reverse ($characters);

      return implode ("", $characters);
      }

      ?>
      General Rules of Thumb
      When deciding whether or not to use a temporary variable, you should
      keep the following 2 questions in mind:
      • Will you be using the variable at least two times?
      • Will the readability of the code be significantly improved?
      If the answer is yes to either of these questions then use the
      variable. Otherwise, turf it and combine function calls (as necessary).

      17. Rewriting existing PHP functions

      A certain PHP source advocated changing the name of the following
      pre-existing function to make it easier for VB programmers to move
      over to PHP:
      <?php

      function len ($str)
      {
      return strlen ($str);
      }
      ?>
      Some users insist on rewriting common PHP functions instead of
      learning the functions the language provides in the first place.
      There are at least two reasons why this should be discouraged. First
      and foremost is that it leads to less readable code. People reading or
      modifying your code will see a bunch of (seemingly) unnecessary
      functions that you have written, and wonder why you defined them in
      this manner rather than using a PHP pre-defined function.
      Defining your own functions in this manner also slows down your
      program. Not only is there more code to be processed, but every time
      you call a user-defined function that imitates a pre-existing
      function, you've added execution time to the function call's overhead.
      Avoid Rewriting Pre-existing PHP Functions
      Let's face it. Sometimes it's hard to resist. After all, a programmer
      can't possibly keep up with all of PHP's functions at once, and who
      has the time to look things up? Why not just rewrite it?
      What I do to avoid rewriting existing PHP functions is to have a copy
      of the PHP Manual handy whenever I'm writing a program (I use the
      indexed PDF version). Then, if I need to write a function that
      "extends" PHP's functionality, I'll peruse through the manual to check
      if that function already exists.
      However, it must be noted, due to the open source nature of PHP, you
      might discover user-defined functions defined before they were added
      to PHP's functionality (such as finding the difference between two
      arrays). This doesn't necessarily mean that you should have to correct
      the code.

      16. Not separating client side from server side

      Some programmers insist on clumping the entire program together,
      meaning the HTML (client-side) with the PHP code (server-side) into
      one enormous file.
      While this may be fine for smaller sites, it can develop into a real
      problem as a site begins to grow bigger and more features are added.
      Programming in this manner can lead to the problem of extremely
      hard-to-maintain and unwieldy files.
      Function API
      When it comes to separating client-side code from server-side code
      there are a couple of options. One method is to create functions that
      will display the dynamically generated content and then place those
      functions in the correct place on the web page.
      The following example illustrates this concept:
      index.php – The Client side
      <?php include_once ("site.lib"); ?>
      <html>
      <head>
      <title> <?php print_header (); ?> </title>
      </head>
      <body>
      <h1> <?php print_header (); ?> </h1>
      <table border="0" cellpadding="0" cellspacing="0">
      <tr>
      <td width="25%">
      <?php print_links (); ?>
      </td>
      <td>
      <?php print_body (); ?>
      </td>
      </tr>
      </table>
      </body>
      </html>
      site.lib – The server side code
      <?php

      $dbh = mysql_connect ("localhost", "sh", "pass")
      or die (sprintf ("Cannot connect to MySQL [%s]: %s",
      mysql_errno (), mysql_error ()));
      @mysql_select_db ("MainSite")
      or die (sprintf ("Cannot select database [%s]: %s",
      mysql_errno (), mysql_error ()));

      $sth = @mysql_query ("SELECT * FROM site", $dbh)
      or die (sprintf ("Cannot execute query [%s]: %s",
      mysql_errno (), mysql_error ()));

      $site_info = mysql_fetch_object ($sth);

      function print_header ()
      {
      global $site_info;
      print $site_info->header;
      }

      function print_body ()
      {
      global $site_info;
      print nl2br ($site_info->body);
      }

      function print_links ()
      {
      global $site_info;

      $links = explode ("\n", $site_info->links);
      $names = explode ("\n", $site_info->link_names);

      for ($i = 0; $i < count ($links); $i++)
      {
      print "\t\t\t
      <a href=\"$links[$i]\">$names[$i]</a>
      \n<br>\n";
      }
      }
      ?>
      As you can see from the above example, separating the client-side code
      from the server-side code adds to the code's readability. Another
      benefit is that once you have your API functions for displaying data,
      you can have your designers go in and change the basic layout of the
      page without requiring you to modify the code.
      Advantages to the function API
      • Relatively clean
      • Fast, almost no overhead
      Disadvantages
      • Not as clean or easy as the template system.
      • Requires some PHP knowledge to modify the template.
      Template System
      Another method for separating client-side code from server-side code
      is to use a template system. That is, to have little placeholders for
      content and then having your program parse the file, replacing each
      placeholder with the necessary information.
      For example you could have a file like:
      <html>
      <head>
      <title>%%PAGE_TITLE%%</title>
      </head>
      <body %%BODY_PROPERTIES%%>
      <h1>%%PAGE_TITLE%%</h1>
      <table border="0" cellpadding="0" cellspacing="0">
      <tr>
      <td width="25%">%%PAGE_LINKS%%</td>
      <td>%%PAGE_CONTENT%%</td>
      </tr>
      </table>
      </body>
      </html>
      You could then write code that would parse the file and replace the
      information inside of the %% delimiters with the appropriate information.
      Note: A good class which enables template systems is the FastTemplate
      class, available from www.thewebmasters.net.
      Advantages to the Template system
      • Extremely clean.
      • No Knowledge of PHP required to modify the template.
      Disadvantages
      • Slower; You need to parse the entire template file and then output it.
      • More complicated to implement.


      15. Using Outdated Paradigms

      Many users seem to use the same outdated code and libraries over and
      over again. For example, they may have written a function using PHP 2
      and still use it with PHP4, even though a function that achieves the
      same purpose was added in PHP3.
      Using outdated paradigms can slow down your script, as well as make it
      unreadable. Readers of your script might not be familiar with PHP's
      outdated functions. Nevertheless, if outdated code is discovered,
      don't feel it is necessary to replace it. Just be sure to avoid using
      this code for future scripting.
      An example of an outdated paradigm, which many programmers seem to
      grasp onto, is the beginControlStructure .. endControlStructure; syntax:
      <?php

      // Bad/Outdated Practice

      while (1):
      print "5";
      if ($idx++ == 5):
      break;
      endif;
      endwhile;

      // Better Practice
      // (the code could be optimized though)

      while (1)
      {
      print "5";
      if ($idx++ == 5) {
      break;
      }
      }

      ?>
      This is a bad practice for the following reasons:
      • It is not widely used, and therefore, many people learning the
      language will be confused by the two syntaxes.
      • It is not compatible with other languages, meaning that it is harder
      to read for people who are transitioning.
      • Most importantly, someday in the future it might be disabled,
      forcing you to rewrite the code that implemented it. Brackets,
      however, will always be a part of the PHP language.
      The above is but one outdated paradigm example seen in a great amount
      of PHP code. There are more. As a rule, you should follow the style
      present in the PHP manual. For the most part it is up to date. It also
      uses the latest functions for its examples. Regularly check the manual
      if you're considering extending PHP's functionality. In this manner,
      you won't end up writing functions that already exist.
      Summary
      In this article we have gone over the first 7 out of the 21 mistakes
      that PHP programmers commit when applying PHP. These textbook mistakes
      are:
      • Misusing the printf() function: printf() should only be used if you
      need to format your output.
      • Misapplying semantics: Many users don't take the time to fully
      understand the finer points of PHP's semantics resulting in buggy and
      error prone code.
      • Lack of inline documentation: Always document your code. Place
      inline documentation above every function, stating the function's
      parameters and purpose. Also make sure to explain particularly
      complicated bits of code, or code that has necessary hacks.
      • Using too many temporary variables: Temporary variables can be used
      to replace multiple function calls or for shortening long-winded
      function sequences.
      • Rewriting pre-existing functions: Always check the manual for an
      appropriate function before you think of writing functionality that
      extends PHP feature set.
      • Not separating client-side code from server-side code: Try to
      modularize your code as much as possible. This makes it significantly
      easier for you and your designers to modify the front-end, while not
      being worried about the back-end code.
      • Using outdated paradigms: Just because you can do something with PHP
      doesn't mean that you should do it. Look to the PHP manual and books
      for the correct way of doing things (Web Application Development with
      PHP and Professional PHP are two excellent books).


      Sterling Hughes
    Your message has been successfully submitted and would be delivered to recipients shortly.