<?php//空间别名namespace ns1;// echo \ns1\ns2\Demo1::hello() .PHP_EOL;// echo ns2\Demo1::hello() .PHP_EOL;// echo ns2\ns3\Demo1::world() .PHP_EOL;//简化命名空间名称: useuse \ns1\ns2\Demo1 as D1;use \ns1\ns2\ns3\Demo1 as D2;echo D1::hello() .PHP_EOL;echo D2::world() .PHP_EOL;namespace ns1\ns2;class Demo1{public static function hello(){return __METHOD__ .'()';}}namespace ns1\ns2\ns3;class Demo1{public static function world(){return __METHOD__ .'()';}}
<?php// 类的自动加载// 原理:将命名空间,映射到类文件的路径上// 1.类名 <->类文件名// 2.类空间 <-> 类文件的路径namespace zhu;// 传统// require __DIR__ . '/admin/controller/Index.php';// require __DIR__ . '/admin/model/User.php';// require __DIR__ . '/admin/view/index/Hello.php';// 注册类的自动加载器spl_autoload_register(function ($class) {// echo $class . PHP_EOL;// 类名:admin\controller\Index// 类文件名: admin\controller\Index.php// 将路径分隔符替换"$path = str_replace('\\', DIRECTORY_SEPARATOR, $class);// echo $path .PHP_EOL;$file = __DIR__. '/' . $path. '.php';if (is_file($file) && file_exists($file)){require $file;} else {die($file . '不存在');}});use admin\controller\Index;use admin\model\User;use admin\view\index\Hello;echo Index::show() .PHP_EOL;echo User::show() .PHP_EOL;echo Hello::show() .PHP_EOL;
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号