UltraMega Blog
2Feb/100

Using a PHP Class to Store Configuration

In a comment on my post listing 5 Tips for Writing Cleaner PHP Code, some good arguments were made against using constants to store configuration variables. The main arguments is that it pollutes the global namespace, which can lead to collisions when implementing other code, and the way it handles typos. This article demonstrates some of the ways constants can fail, and shows an alternative.

So here is how to store these constants in a class to avoid these problems. This puts the constants in their own namespace and prevent mistakes later on.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<?php
 
// Declaring your config class constants
class Config {
    const DB_HOST     = 'localhost',
          DB_USER     = 'username',
          DB_PASS     = 'password',
          ANOTHER_VAR = true;
}
 
echo Config::DB_HOST; // outputs localhost
 
echo Config::USER; // PHP Fatal error
 
if(Config::ANOTHER_VAR) {
    // do something
}
 
?>

That's all there is to it. Now all your constants are consolidated under one namespace and any typos will result in a fatal error. You can name the class whatever you want to be unique and avoid any collisions.

16Jun/090

5 Tips for Writing Cleaner PHP Code

There are many benefits to writing clean code for any project, no matter how small. The most obvious benefit is that it is easier for you to read and edit, especially when you come back after a long break. This is even more important when someone else comes in to modify your code. The importance of clean code becomes most apparent when you need to find an error, especially a syntax error. In the end, cleaner code means less time reading and more time coding!

These are 5 tips that I use and recommend. I know there are plenty of lists like this, but I hope you learn at least one new trick...

29May/090

Snippet: Autoloading Objects (PHP 5)

When writing the PHP that powers TempServers, I wrote the core functions into classes for better organization and efficiency. To make things further organized, each class is stored in individual source files, no matter how small. The problem here is keeping track of which classes are used where, in order to include the appropriate source files. Fortunately, PHP 5 offers a solution: autoloading.

This comes in the form of the __autoload function which automatically gets called if a class is called that does not exist. Here's what it looks like:

function __autoload($class) {
    require_once(strtolower($class) . '.class.php');
}

Usage

  1. Place each PHP class in individual files named after the class followed by .class.php (Example: class MyClass goes in a file named myclass.class.php).
  2. Include the code snipped above into any file that might use one of your classes.

For more details, check out the PHP manual: http://www.php.net/manual/language.oop5.autoload.php