dpf5207 2010-03-26 03:20
浏览 30
已采纳

是否可以基于PHP中的命名空间自动加载文件?

Would what mentioned in the title be possible? Python module style that is. See this example for what I exactly mean.

index.php

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

Hello/World.php

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

Would this be possible?

  • 写回答

1条回答 默认 最新

  • duanqianruan8448 2010-03-26 03:32
    关注

    Yes, have a look at the example of 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;
    

    The above example will output something similar to:

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

    Here is a link to a Autoloader builder, that

    is a command line application to automate the process of generating an autoload include file.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?