PHP 命名空间全局


PHP Namespace Global

有没有办法让 PHP 命名空间允许在命名空间内调用函数,就好像它们是全局的一样?

例:

handle()

而不是:

prggmr'handle()

这是我的示例代码:

<?php
require_once 'prggmr/src/prggmr.php';
prggmr'handle(function() {
  echo 'This is a test scenario';
}, 'test');
prggmr'signal('test');

别名不适用于以下函数:

<?php
require 'prggmr/src/prggmr.php';
use prggmr'handle;
handle(function(){
    echo "Test";
}, "test");

结果:

Fatal error: Call to undefined function handle()

据我了解,文档中的这段摘录说这是不可能的......

函数和常量都不能通过 use 语句导入。

源:

http://www.php.net/manual/en/language.namespaces.faq.php#language.namespaces.faq.nofuncconstantuse

不适用于整个命名空间,不。但是对于单名,你可以

use p'handle;

别名p'handle只是handle.

以为我会为现代PHP添加一个答案,因为我最近了解到:

在 PHP 5.6 之前,函数和常量都不能通过 use 语句导入。 从 PHP 5.6 开始,允许别名或导入函数和常量名称。

因此,您的第二个代码示例现在应该可以正常工作。

另外值得一提的是,您可以为 PHP 命名空间定义块范围,尽管不鼓励这样做。所以这将起作用:

<?php
require_once 'prggmr/src/prggmr.php';
namespace prggmr {
    handle(function() {
      echo 'This is a test scenario';
    }, 'test');
    signal('test');
}