Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autoload with namespaces in PHP 5.3?

How do you use _autoload in PHP 5.3 with namespaces? I have a main autoload function in a namespace separate from my script. I'm also calling a class with a different namespace. (It's not surprising, but) It's not finding the autoload function. Do I have to recreate the autoload function for each namespace? That seems suboptimal.

Thanks in advance for any help!

like image 903
M3Mania Avatar asked Aug 30 '09 21:08

M3Mania


People also ask

What is Namespacing in PHP?

A namespace is a hierarchically labeled code block holding a regular PHP code. A namespace can contain valid PHP code. Namespace affects following types of code: classes (including abstracts and traits), interfaces, functions, and constants. Namespaces are declared using the namespace keyword.

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 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.

Does PHP support namespace?

In the PHP world, namespaces are designed to solve two problems that authors of libraries and applications encounter when creating re-usable code elements such as classes or functions: Name collisions between code you create, and internal PHP classes/functions/constants or third-party classes/functions/constants.


1 Answers

From a comment in the PHP manual:

To use autoload function with namespaces you should remember to define it in main scope in "\" namespace.

like image 123
VoteyDisciple Avatar answered Sep 19 '22 14:09

VoteyDisciple