【问题标题】:Autoloading constants in PHP?在 PHP 中自动加载常量?
【发布时间】:2023-03-20 17:31:02
【问题描述】:

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

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 没有像类一样调用常量,这给我留下了 Undefined constant 错误。

我可以通过某种方式模拟__autoload 类的常量吗?

【问题讨论】:

    标签: php constants autoload


    【解决方案1】:

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

    <?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() 按您的预期工作。

    【讨论】:

    • 谢谢!这看起来很有希望。虽然我不喜欢将它们包装在虚拟类中,但它似乎有效。
    【解决方案2】:

    使用未定义的常量会引发 PHP 警告。

    您可以编写自定义错误处理程序来捕获警告并加载到适当的常量文件中。

    【讨论】:

    • 感谢您的建议。不幸的是,Undefiend constant 错误是一个致命错误 (E_ERROR),自定义处理程序无法捕获。
    • 嗯。当然它曾经是一个通知,但我没有使用 5.3。
    • 无论如何也行不通。刚刚在 5.2 中试了一下,当然,触发错误的行已经被处理,所以直到下一行才会获取常量定义。希望你能得到解决方案。
    猜你喜欢
    • 2011-09-05
    • 2019-08-19
    • 1970-01-01
    • 2014-10-17
    • 2016-04-13
    • 2020-03-31
    • 1970-01-01
    • 2020-08-27
    • 1970-01-01
    相关资源
    最近更新 更多