即使 PHP 有命名空间并且可以直接在类之外声明函数,我强烈建议您至少使用静态类方法。然后你就不必乱搞了,并且会使用命名空间,因为它们被设计为可以工作;与类。
这是一个工作示例:
你好.php
<?php
namespace Project\B;
class HelloClass {
static function hello() {
echo "Hello from hello.php!";
}
}
一个.php
<?php
namespace Project\A;
require('hello.php'); // still have to require the file, unless you have an autoloader
use \Project\B\HelloClass; // import this class from this namespace
\Project\B\HelloClass::hello(); // calling it this way render the 'use' keyword obsolete
HelloClass::hello(); // or use it as it is declared
**注意**:use foo as bar;
让我们重命名类!例如 :
use \Project\B\HelloClass as Foo; // import this class from this namespace as Foo
Foo::hello(); // calling it this way using the 'use' keyword and alias
** 更新 **
有趣的是,您可以这样做:
c.php
namespace Project\C;
function test() {
echo "Hello from test!\n";
}
一个.php
use \Project\C; // import namespace only
use \Project\C as Bar; // or rename it into a different local one
C\test(); // works
Bar\test(); // works too!
因此,只需编写use Project\Library as L;
和调用L\hello();
. 我认为这是你最好的选择。