Categorized | Best practices, News, OOP, PHP

Tags |

Advantages of using the PEAR class naming convention

Posted on 09 March 2005 by Demian Turner

There are many good reasons for following the PEAR coding standards which I don’t have time to go into now, a slightly elabourated version of the ‘rules’ is available here, mostly borrowed from the Horde project.

But by far the most convincing reason to use the file naming convention, which means that a class located in your include path like Foo/Bar/Baz.php is called Foo_Bar_Baz, is the ability to take advantage of PHP 5’s __autoload magic method.

What this means is that if you instantiate the above class, and forgot to require it, it can be located and loaded automatically, from any of hundreds of classes in your include path. Here’s the code:

function __autoload($class)
{
  $filename = str_replace('_', '/', $class) . '.php';
  @require_once $filename;
}
Bookmark and Share

6 Comments For This Post

  1. bubblenut Says:

    Shouldn’t that be

    
    function __autoload($class)
    {
      $filename = strreplace('_', DIRECTORY_SEPERATOR, $class) . '.php';
      @require_once $filename;
    }
    

    ;p

  2. demian Says:

    as far as I remember, the DIRECTORY_SEPARATOR constant is only available once you load PEAR.php, if you have this all the better.

    cheers

    Demian

  3. John Wyles Says:

    I think you both mean: “str_replace” :o)

  4. Paul M. Jones Says:

    Hi Demian — PATH_SEPARATOR and DIRECTORY_SEPARATOR are both available directly in recent 4.x branches (although earlier versions did not have both).

  5. Claus Jørgensen Says:

    Great idea, funny enough never though of this.

    Btw. DIRECTORY_SEPARATOR is a PHP constant, not a PEAR constant.

  6. Lorenzo Alberton Says:

    A clarification note (i.e. an excuse to say ‘hallo!’):

    DIRECTORY_SEPARATOR is available since PHP 4.0.6.
    You probably meant ‘PATH_SEPARATOR’, which was introduced with PHP 4.3.0-RC2, and is defined in PEAR.php if the PHP version in use is lower.
    Anyway, str_replace(‘_’, ‘/’, $class) will work just fine on every platform.

    cheers

Leave a Reply

Categories

Books

Demian Turner's currently-reading book recommendations, reviews, favorite quotes, book clubs, book trivia, book lists

Facebook