1 <?php 2 /** 3 * @Author: Martin 4 * @Support: Martin 5 * @Last Modified by: Martin 6 */ 7 namespace Order; 8 9 const STR = 'order list<br />';10 11 function detail()12 {13 return 'order detail<br />';14 }15 function call_by_self()16 {17 return 'call by self<br />';18 }19 /**20 *21 */22 class Orderlist23 {24 25 public function __construct()26 {27 echo 'Class NameSpace is "', __NAMESPACE__, '"';28 }29 public function show_list()30 {31 for ($i = 0; $i < 5; $i++) {32 echo "<ul><li>this is order$i<br />";33 //内部直接访问34 echo detail();35 echo "</li></ul>";36 }37 }38 }39 //内部通过命名空间访问40 echo Ordercall_by_self();
index.php 内容为:
1 <?php 2 /** 3 * @Author: Martin 4 * @Support: Martin 5 * @Last Modified by: Martin 6 */ 7 namespace index; 8 include_once('Order.php'); 9 10 //外部访问class 实例化即可使用11 use OrderOrderlist;12 $orderlist = new orderlist;13 $orderlist->show_list();14 15 //外部访问静态变量和function 直接访问16 use Order;17 echo OrderSTR;18 echo Orderdetail();
打印结果为:
User.php 内容为:
1 namespace User;2 //直接载入Order3 #include('Order.php');4 //自动载入5 spl_autoload_register(function($className) {6 var_dump($className);7 });8 spl_autoload_call('Order');
打印结果为:
SPL自动载入函数包含如下:
修改User.php 如下:
1 namespace User; 2 3 //直接载入Order 4 #include('Order.php'); 5 //自动载入 6 define('LIB_DIR', __DIR__ . DIRECTORY_SEPARATOR . 'lib' . DIRECTORY_SEPARATOR); 7 spl_autoload_register(function ($class) { 8 $path = LIB_DIR . $class . '.lib.php'; 9 include ($path);10 });11 12 spl_autoload_call('Order');13 use Order;14 15 $orderList = new OrderOrderlist();16 $orderList->show_list();
打印结果为: