假设项目目录下有A.php,B.php,C.php和index.php
A.php中的代码
<?php namespace a\a; class Apple{ public function get_info(){ echo 'this is A'; } } ?>B.php中的代码
<?php namespace a\b; class Apple{ public function get_info(){ echo 'this is B'; } } ?>C.php中的代码
<?php //没有命名空间,这样的类是顶级类 class Apple{ public function get_info(){ echo 'this is C'; } } ?>index.php中代码
<?php //引入三个类 require_once 'A.php'; require_once 'B.php'; require_once 'C.php'; //使用某个命名空间 use a\a; //实例化类A $a1 = new Apple(); $a1->get_info();#这里打印出来的this is A //实例化类B,当前文件已经使用了命名空间a\a,就不能在使用a\b了,否则又会混淆Apple类,但一个文件中可使用多个命名空间,只要不冲突 $b1 = new a\b\Apple(); $b1->get_info();#这里打印出来的是this is B //实例化类C,C是顶级类,在前面加上\表明 $c1 = new \Apple(); $c1->get_info();#这里打印出来的是this is C ?>学习来源:https://www.imooc.com/video/7834/0