luyj 发表于 2014-12-23 08:27:25

php命名空间自动加载后使用单独类include使用

                      普通的命名空间自动加载后,又对框架不熟,在M层或者C层想include直接调用第三方类时通常都不行会报错。原因是有命名空间和自动加载这两个php特性制约。

要解决这两个问题就只要两步即可,但当然在正规项目中不建议使用,要遵循MVC和PCR-0(1.只有一个入口文件;2.在类文件中不能使用直接实现方法的写法;3.命名空间与绝对路径一致)法则,这只是一个偏门技巧。
解决方法

[*]在include文件后,用spl_autoload_unregister()把自动加载的函数注销掉;

    如:spl_autoload_unregister('\\Test\\Loader::autoload');

   但在运用完第三方类的时候要马上把之前的自动加载函数运行一次,不然其他方法加载不了会报错。
      \main\Test1::test();
        spl_autoload_register('\\Test\\Loader::autoload');
2.   第三方类要加上单独的命名空间,不然在使用的时候会,include类会以当前的命名空间来使用。如果加载类不是在跟当前命名空间同一个目录,就会报错。

贴其中一个类代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
namespace Test;

class Factory
{
   
    public static function createDatabase()
    {
      $db = new Database();
      Register::set('db1',$db);
      include BASEDIR.'/Test1.php';
      spl_autoload_unregister('\\Test\\Loader::autoload');
      \main\Test1::test();
      spl_autoload_register('\\Test\\Loader::autoload');
         
      return   $db;
    }   
}





最终还是叮嘱不建议程序用这个,尽量遵守面向过程的编程方法。

                   

页: [1]
查看完整版本: php命名空间自动加载后使用单独类include使用