views:

286

answers:

2

Hey all.

I was hoping that if I were to define constants in a separate namespace, like:

<?php
namespace config\database\mysql;

const HOST = 'localhost';
const USER = 'testusr';
const PASSWORD = 'testpwd';
const NAME = 'testdb';

?>

That I would be able to use __autoload to automatically include them:

<?php
function __autoload($className)
{
    echo "Autoload: {$className}\n";
    $class_file = str_replace('\\', '/', $className) . ".php";
    if(file_exists($class_file)) {
        include $class_file;
    }
}

echo config\database\mysql\HOST;
?>

This, however, does not work. The __autoload is not called for the constant as it is with classes, leaving me with a Undefined constant error.

Does anybody know a workaround? Something I am missing.
Some way that I can use to simulate the class __autoload for constants?

Thanks.

A: 

Using an undefined constant will throw a PHP warning.

You can write a custom error handler to catch the warning and load in the appropriate constants file.

Mike
That's not what Atli is asking...
Alix Axel
Thanks for the suggestion. Unfortunately the `Undefiend constant` error is a fatal error (`E_ERROR`), which a custom handler can't catch.
Atli
Hmm. Sure it used to be a notice, but I'm not using 5.3.
Mike
Wouldn't have worked anyway. Just gave it a try in 5.2 and, of course, the line triggering the error has already been processed so the constant definition isn't picked up until the next line. Hope you get a solution.
Mike
+3  A: 

Try this (worked on my server):

<?php
namespace config\database\mysql;

class Mysql
{
    const HOST = 'localhost';
    const USER = 'testusr';
    const PASSWORD = 'testpwd';
    const NAME = 'testdb';
}
?>

<?php
function __autoload($className)
{
    echo "Autoload: {$className}\n";
    $class_file = str_replace('\\', '/', $className) . ".php";
    if(file_exists($class_file)) {
        include $class_file;
    }
}

echo config\database\mysql\Mysql::HOST;
?>

Basically you need to create a class to act as a wrapper for the constants but by doing so it allows __autoload() to work as you intended.

John Conde
Thanks! This looks promising. I'm not to fond of having to wrap them up in dummy classes though, but it seems to work.
Atli