标题PHP use、namespace和自动加载的关系

  1. PHP一个文件要想执行另一个文件的代码,一定要先引入 (require_once)
  2. 使用use的话,一定要有被use的那个空间,也就是说所有被引入的文件里面一定要有那个namespace
  3. 通过use的空间,可以使用自动加载函数加载文件
// ./index.php
 
spl_autoload_register(function($class_name) { 
   $file = str_replace("\\", "/", dirname(__FILE__) . "/" . $class_name . ".php"); 
   if(file_exists($file)) { 
       require_once($file);#    } 
   } 
}); 
use helper\PrintClass; 
$obj = new PrintClass(); 
$obj->doPrint(); 
// ./helper/PrintClass.php
 
namespace helper; 
class PrintClass { 
    public function doPrint() { 
        echo "开始打印"; 
    } 
} 

你可能感兴趣的:(PHP,namespace,use,自动加载)