Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to autoload a file based on the namespace in 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?

like image 724
izym Avatar asked Mar 26 '10 11:03

izym


People also ask

What is the relation of Namespacing and autoloading PHP files?

Basically it says: "inside this directory, all namespaces are represented by sub directories and classes are <ClassName>. php files." Autoloading is PHP's way to automatically find classes and their corresponding files without having to require all of them manually.

What is an autoloader in PHP?

Autoloading in the “Olden Days” PHP 5 introduced the magic function __autoload() which is automatically called when your code references a class or interface that hasn't been loaded yet. This provides the runtime one last chance to load the definition before PHP fails with an error.

How do you autoload in PHP?

The spl_autoload_register() function registers any number of autoloaders, enabling for classes and interfaces to be automatically loaded if they are currently not defined. By registering autoloaders, PHP is given a last chance to load the class or interface before it fails with an error.

What does the function SPL autoload register do in PHP?

Parameters ¶ If null , then the default implementation of spl_autoload() will be registered. This parameter specifies whether spl_autoload_register() should throw exceptions when the callback cannot be registered.


1 Answers

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.

like image 147
Gordon Avatar answered Sep 27 '22 22:09

Gordon