raw code

Global Constants with PHP

Robert Eisele

There are certainly many possibilities to create a global config-file for your web project. You could create a global configuration file for your defines, which you have to include in every file. Better is an automatic include by the auto_prepend_file directive in your php.ini.

The problem here is the word "include". For every include you need hard drive access and have the parse- and cast-overhead for the directives. Someone could say that you could install an op-cache and the problem is cleared. Okay thats quite right. Some good op-code caches do also mmap variables and constants. But not in every case an op-cache is appropriate. Consequently it's difficult to have constants available everytime and above all global.

For this problem I wrote the PHP-Extension defcon - define constant. defcon is able to define constants in a seperate config file, which is available after server startup. In addition it's a nice spin-off that you have no parsing and execution overhead; everything is held in memory like core constants such as M_PI, TRUE/FALSE, PHP_INT_MAX, ....

Another advantage is security. You don't need to have your secret authentication data for your database or something else in the docroot and even if you like the contended safe mode you can use defcon, too.

Okay, long story cut short. Let's come to the details of defcon. By default you have a config file in /etc/defcon.conf where you can define the constants in a C-like syntax.

# Database Config
string DBHOST = "localhost";
string DBUSER = "root";
string DBPASS = "";
string DBNAME = "test";

# Parsertest
int T1 = 123;
int T2 = 1.3;
int T3 = "test";
real T4 = 1;

string T5 = hello # should work too

logical T6 = true;
logical T7 = false;
logical T8 = 234

On PHP side you can access the constants by writing ...

<?php
var_dump(DBHOST);
?>

... for example. What do we see? Right, we see the expected output:

string(9) "localhost"

The parser is very flexible. As you can see, you not have to quote single-token strings and all entrys are typesafe. You can assign constants with every value and they will be casted in normal PHP-manner. A few words to the datatypes at the end of this demonstration. There are many datatypes available that are not available in PHP. But to have a bigger list I defined alias names depending on the names of other languages.

Go to the Defcon Project Page

If you don't see any sense in PHP-defcon: This project is surely only a proof of concept for writing a flexible config-parser. But combined with the positve aspects of above I have to say that I use PHP-defcon in my own projects.