Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are some useful PHP Idioms?

I'm looking to improve my PHP coding and am wondering what PHP-specific techniques other programmers use to improve productivity or workaround PHP limitations.

Some examples:

  1. Class naming convention to handle namespaces: Part1_Part2_ClassName maps to file Part1/Part2/ClassName.php

  2. if ( count($arrayName) ) // handles $arrayName being unset or empty

  3. Variable function names, e.g. $func = 'foo'; $func($bar); // calls foo($bar);

like image 827
Andrew Whitehouse Avatar asked Oct 28 '08 13:10

Andrew Whitehouse


4 Answers

Ultimately, you'll get the most out of PHP first by learning generally good programming practices, before focusing on anything PHP-specific. Having said that...


Apply liberally for fun and profit:

  1. Iterators in foreach loops. There's almost never a wrong time.

  2. Design around class autoloading. Use spl_autoload_register(), not __autoload(). For bonus points, have it scan a directory tree recursively, then feel free to reorganize your classes into a more logical directory structure.

  3. Typehint everywhere. Use assertions for scalars.

    function f(SomeClass $x, array $y, $z) {
        assert(is_bool($z))
    }
    
  4. Output something other than HTML.

    header('Content-type: text/xml'); // or text/css, application/pdf, or...
    
  5. Learn to use exceptions. Write an error handler that converts errors into exceptions.

  6. Replace your define() global constants with class constants.

  7. Replace your Unix timestamps with a proper Date class.

  8. In long functions, unset() variables when you're done with them.


Use with guilty pleasure:

  1. Loop over an object's data members like an array. Feel guilty that they aren't declared private. This isn't some heathen language like Python or Lisp.

  2. Use output buffers for assembling long strings.

    ob_start();
    echo "whatever\n";
    debug_print_backtrace();
    $s = ob_get_clean();
    

Avoid unless absolutely necessary, and probably not even then, unless you really hate maintenance programmers, and yourself:

  1. Magic methods (__get, __set, __call)

  2. extract()

  3. Structured arrays -- use an object

like image 148
Preston Avatar answered Nov 10 '22 10:11

Preston


My experience with PHP has taught me a few things. To name a few:

  • Always output errors. These are the first two lines of my typical project (in development mode):
ini_set('display_errors', '1');
error_reporting(E_ALL);
  • Never use automagic. Stuff like autoLoad may bite you in the future.

  • Always require dependent classes using require_once. That way you can be sure you'll have your dependencies straight.

  • Use if(isset($array[$key])) instead of if($array[$key]). The second will raise a warning if the key isn't defined.

  • When defining variables (even with for cycles) give them verbose names ($listIndex instead of $j)

  • Comment, comment, comment. If a particular snippet of code doesn't seem obvious, leave a comment. Later on you might need to review it and might not remember what it's purpose is.

Other than that, class, function and variable naming conventions are up to you and your team. Lately I've been using Zend Framework's naming conventions because they feel right to me.

Also, and when in development mode, I set an error handler that will output an error page at the slightest error (even warnings), giving me the full backtrace.

like image 33
changelog Avatar answered Nov 10 '22 08:11

changelog


Fortunately, namespaces are in 5.3 and 6. I would highly recommend against using the Path_To_ClassName idiom. It makes messy code, and you can never change your library structure... ever.

The SPL's autoload is great. If you're organized, it can save you the typical 20-line block of includes and requires at the top of every file. You can also change things around in your code library, and as long as PHP can include from those directories, nothing breaks.

Make liberal use of === over ==. For instance:

if (array_search('needle',$array) == false) {
  // it's not there, i think...
}

will give a false negative if 'needle' is at key zero. Instead:

if (array_search('needle',$array) === false) {
  // it's not there!
}

will always be accurate.

like image 20
Lucas Oman Avatar answered Nov 10 '22 10:11

Lucas Oman


See this question: Hidden Features of PHP. It has a lot of really useful PHP tips, the best of which have bubbled up to the top of the list.

like image 42
nickf Avatar answered Nov 10 '22 08:11

nickf