开发者

Autoloading constants in PHP?

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

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开发者_StackOverflow:

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.

Some way that I can simulate the class __autoload for constants?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜