PHP 中自动加载常量?

发布于 2024-08-18 07:13:04 字数 611 浏览 1 评论 0原文

我希望如果我要在单独的命名空间中定义常量,例如:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

迷雾森÷林ヴ 2024-08-25 07:13:04

试试这个(在我的服务器上工作):

<?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;
?>

基本上,您需要创建一个类来充当常量的包装器,但这样做可以让 __autoload() 按您的预期工作。

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.

叫嚣ゝ 2024-08-25 07:13:04

使用未定义的常量将引发 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文