开发者

Is it possible to autoload a file based on the namespace in PHP?

开发者 https://www.devze.com 2022-12-24 13:56 出处:网络
Would what mentioned in the title be possible? Python module style that is. See this example for what I exactly mean.

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 gre开发者_运维百科et() { echo 'Hello, World!'; }

Would this be possible?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号