PHP 中自动加载常量?
我希望如果我要在单独的命名空间中定义常量,例如:
namespace config\database\mysql;
const HOST = 'localhost';
const USER = 'testusr';
const PASSWORD = 'testpwd';
const NAME = 'testdb';
我将能够使用 __autoload 自动包含它们:
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;
但是,这是行不通的。不像类那样为常量调用 __autoload ,这给我留下了 未定义常量
错误。
我可以通过某种方式模拟常量类__autoload
吗?
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:
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
试试这个(在我的服务器上工作):
基本上,您需要创建一个类来充当常量的包装器,但这样做可以让 __autoload() 按您的预期工作。
Try this (worked on my server):
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.
使用未定义的常量将引发 PHP 警告。
您可以编写自定义错误处理程序来捕获警告并加载到适当的常量文件中。
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.