Example:
#/db/mysql.class.php is the DB folder with MySql.class.php file namespace Db;class mysql{public function __construct () { Var_dump (__file__); }}
#/index.phpnamespace home;use db\mysql; $mysql = new MySql ();
Error
Fatal error: Class ‘DB\MySql‘ not found in D:\localhost\demo\space\index.php on line 23
Modify
Change the index.php to the following, yes, but why can't it be loaded automatically?
namespace Home;use db\mysql;spl_autoload_register (function ($class) { if ($class) { $file = str_replace (' \ \ ', ' /', $class); $file. = '. class.php '; if (file_exists ($file)) { include $file; }}} ); $mysql = new MySQL ();
Points:
First:
Namespaces are not directly related to file loading, just some languages, which correspond to named spatial structures and file structures. In PHP, for example, the general namespace structure, and the PHP file structure is a mapping relationship, through the name of the namespace, you can figure out the actual storage location of the class, and then instantiate the time, will trigger the use of the set SPL auto-load function to introduce the file.
(Xee: namespaces are imported in advance via auto-import or Include,require, and then automatically loaded according to the namespace)
Second:
namespace Home;use db\mysql; $mysql = new MySql ();
The actual execution of the code is new \DB\MySql(); not found when the file will call your AutoLoad function and file_exists("DB/MySql.class.php") , in the current directory to find the file, in the case can not be found, and then you see the error
(Xee: In the called MySql.class.php file, there is also a \db\mysql namespace)
Third:
If you are just beginning to understand the PHP namespace, see How to use the PHP namespace, and turn over the source code of the framework using the namespace, such as Micro-mvc,slim.
and psr-4--'s freshly baked PHP specification, which includes this:
* //Register the base directories for the namespace prefix * $loader->addnamespace (' Foo\bar ', '/path/to/ Packages/foo-bar/src '); * $loader->addnamespace (' Foo\bar ', '/path/to/packages/foo-bar/tests ');
Fourth:
We often use db\mysql, this form of namespace! Not necessarily use \ This backslash, but also can be used for example: Db::mysql, or db_mysql, etc., to be analyzed in the function method of the auto-find class.
< reference: Php namespaces namespace How to implement automatic loading >
PHP uses namespaces (namespace) for automatic loading