命名空间及自动加载函数的使用

来源:互联网 发布:主数据和元数据区别 编辑:程序博客网 时间:2024/06/12 00:26

结合__autoload函数或spl_autoload_register函数使用命名空间。以下是使用范例,加上原始加载一共介绍三种使用方法。

代码布局:主目录namespace,下级目录AutoFolder,主目录下有index.php入口文件,AutoFolder下有autoload.php和Order.php文件。

index.php

<?phpinclude_once('AutoFolder/autoload.php');$order = new AutoFolder\Order();$order->showName();

autoload.php

<?php// namespace AutoFolder; #使用命名空间时,只有方法一能用,其他均受限制,方法三需要在spl_autoload_register方法中加入命名空间指定loader方法//方法一:直接载入require('Order.php');   //方法二:使用__autoload函数/*function __autoload($class)   {   $file = $class . '.php';   if (is_file($file)) {   require_once($file);   }   }*///方法三:使用自动函数注册/*function loader($class)   {   $file = $class . '.php';   if (is_file($file)) {   require_once($file);   }   }   spl_autoload_register('loader');   *///方法三扩展:使用类方法/*class Loader   {   public static function loadClass($class)   {   $file = $class . '.php';   if (is_file($file)) {   require_once($file);   }   }   }   spl_autoload_register(array('Loader', 'loadClass')); */?>


Order.php

<?phpnamespace AutoFolder;class Order{    public function __construct()    {        echo 'Class NameSpace is "', __NAMESPACE__, '"';    }    public function showName()    {        echo "<ul><li>I am Order<br />";    }}


通过index.php加载,然后分别打开注释看实现。

0 0