Constant autoload in PHP?

I was hoping that if I defined constants in a separate namespace, for example:

namespace config\database\mysql; const HOST = 'localhost'; const USER = 'testusr'; const PASSWORD = 'testpwd'; const NAME = 'testdb'; 

So that I can use __autoload to automatically enable them:

 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. __autoload not called for a constant, as is the case with classes, leaving me with an Undefined constant error.

Is there some way I can model the __autoload class for constants?

+6
php const autoload
source share
2 answers

Try this (works 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 work as a shell for constants, but at the same time it allows __autoload () to work the way you planned.

+7
source share

Using the undefined constant will trigger a PHP warning.

You can write your own error handler to catch the warning and load it into the corresponding constant file.

0
source share

All Articles