【问题标题】:Is it possible to autoload a file based on the namespace in PHP?是否可以根据 PHP 中的命名空间自动加载文件?
【发布时间】:2011-02-01 03:24:53
【问题描述】:

标题中提到的内容可能吗? Python 模块样式就是这样。请参阅此示例了解我的确切含义。

index.php

<?php
use Hello\World;
World::greet();

你好/World.php

<?php
namespace Hello\World;
function greet() { echo 'Hello, World!'; }

这可能吗?

【问题讨论】:

    标签: php python module namespaces autoload


    【解决方案1】:

    是的,看看spl_autoload_register的例子

    namespace Foobar;
    
    class Foo {
        static public function test($name) {
            print '[['. $name .']]';
        }
    }
    
    spl_autoload_register(__NAMESPACE__ .'\Foo::test'); // As of PHP 5.3.0
    
    new InexistentClass;
    

    上面的例子会输出类似于:

    [[Foobar\InexistentClass]]
    Fatal error: Class 'Foobar\InexistentClass' not found in ...
    

    这是Autoloader builder的链接,

    是一个命令行应用程序,用于自动生成自动加载包含文件的过程。

    【讨论】:

    • 所以似乎只能与类有关。我只需要忍受这个:)
    猜你喜欢
    • 1970-01-01
    • 2013-11-25
    • 2014-04-13
    • 2011-04-08
    • 2021-04-04
    • 2011-08-06
    相关资源
    最近更新 更多