1

这是一个在单个文件中使用 PHP 命名空间/自动加载的实验。

namespace trust;

class trust_network{        
    public function __construct(){      
        print "SUP";
    }
}

namespace trust2;

$trust = new \trust\trust_network(); $do = new \test();

function __autoload($class){
    require($class.".php");     
    print $class;
}

所以在命名空间 trust2 下,我调用“\test”——也就是我想从全局基础上的外部文件自动加载该类。我写的东西不起作用。我知道我在命名空间下有 __autoload,但是如何在全局基础上声明它?不能在命名空间声明之前包含。

4

2 回答 2

3

对于一个文件中的多个命名空间,您应该使用大括号语法:

namespace n1 {
...
}
namespace n2 {
...
}
namespace {
...
}

在最后一个块中,您可以在全局命名空间中声明函数。参考:http ://www.php.net/manual/en/language.namespaces.definitionmultiple.php

于 2013-02-21T18:32:38.667 回答
2

自动加载通常是为了让您可以为每个文件放置一个类。因此,您应该具有以下布局

/index.php

function __autoload($class){
    // You may need to convert backslashes in $class to forward slashes 
    // and strip the first slash, we'll leave the
    require($class.".php");
    // debug-only:  print $class;
}
// Calling new here triggers __autoload to be called
$trust = new \trust\trust_network();
$do = new \test();

/trust/trust_network.php

namespace trust;

class trust_network{        
    public function __construct(){      
        print "TRUST_NETWORK";
    }
}

/test.php

class test() {
    public function __construct(){      
        print "TEST";
    }
}

请注意,您应该改用spl_autoload_register,因为它允许多个系统挂钩自己的自动加载行为。从 PHP 5.3 开始,您可以执行以下操作

spl_autoload_register(function ($class) {
    require($class.".php");
});
于 2013-02-21T18:36:35.260 回答