调用在没有前缀的另一个命名空间中定义的PHP函数

时间:2010-07-28 22:34:59

标签: php function namespaces

在命名空间中定义函数时,

namespace foo {
    function bar() { echo "foo!\n"; }
    class MyClass { }
}

从另一个(或全局)命名空间调用命名空间时必须指定命名空间:

bar();          // call to undefined function \bar()
foo\bar();      // ok

对于类,您可以使用“use”语句将类有效地导入当前命名空间[编辑:我认为您可以“使用foo”来获取类,但显然不是。]

use foo\MyClass as MyClass;
new MyClass();  // ok, instantiates foo\MyClass

但这不适用于函数[并且考虑到有多少函数会很笨拙]:

use foo\bar as bar;
bar();          // call to undefined function \bar()

您可以对命名空间进行别名,以使前缀更短,以便输入

use foo as f;   // more useful if "foo" were much longer or nested
f\bar();        // ok

但有没有办法完全删除前缀?

背景:我正在研究Hamcrest匹配库,它定义了很多工厂函数,其中许多都是嵌套的。拥有名称空间前缀确实会破坏表达式的可读性。比较

assertThat($names, 
    is(anArray(
        equalTo('Alice'), 
        startsWith('Bob'), 
        anything(), 
        hasLength(atLeast(12))
    )));

use Hamcrest as h;
h\assertThat($names, 
    h\is(h\anArray(
        h\equalTo('Alice'), 
        h\startsWith('Bob'), 
        h\anything(), 
        h\hasLength(h\atLeast(12))
    )));

3 个答案:

答案 0 :(得分:35)

PHP 5.6允许使用use关键字导入函数:

namespace foo\bar {
    function baz() {
        echo 'foo.bar.baz';
    }
}

namespace {
    use function foo\bar\baz;
    baz();
}

有关详细信息,请参阅RFC:https://wiki.php.net/rfc/use_function

答案 1 :(得分:7)

通过添加下面提到的帮助程序,您可以通过调用以下命令将所有内容从Hamcrest命名空间导入到当前命名空间:

import_namespace('Hamcrest', __NAMESPACE__);

以下是黑客攻击,function_alias的工作方式与http://www.php.net/manual/en/function.class-alias.php类似,除非在函数上有效:

function function_alias ($original, $alias) {

  $args = func_get_args();
  assert('count($args) == 2', 'function_alias(): requires exactly two arguments');
  assert('is_string($original) && is_string($alias)', 'function_alias(): requires string arguments');

  // valid function name - http://php.net/manual/en/functions.user-defined.php
  assert('preg_match(\'/^[a-zA-Z_\x7f-\xff][\\\\\\\\a-zA-Z0-9_\x7f-\xff]*$/\', $original) > 0',
"function_alias(): '$original' is not a valid function name");
  assert('preg_match(\'/^[a-zA-Z_\x7f-\xff][\\\\\\\\a-zA-Z0-9_\x7f-\xff]*$/\', $alias) > 0',
    "function_alias(): '$alias' is not a valid function name");

  $aliasNamespace = substr($alias, 0, strrpos($alias, '\\') !== false ? strrpos($alias, '\\') : 0);
  $aliasName = substr($alias, strrpos($alias, '\\') !== false ? strrpos($alias, '\\') + 1 : 0);
  $serializedOriginal = var_export($original, true);

  eval("
    namespace $aliasNamespace {
      function $aliasName () {
        return call_user_func_array($serializedOriginal, func_get_args());
      }
    }
  ");

}

与名称空间导入器结合使用:

function import_namespace ($source, $destination) {

  $args = func_get_args();
  assert('count($args) == 2', 'import_namespace(): requires exactly two arguments');
  assert('is_string($source) && is_string($destination)', 'import_namespace(): requires string arguments');

  // valid function name - http://php.net/manual/en/functions.user-defined.php
  assert('preg_match(\'/^([a-zA-Z_\x7f-\xff][\\\\\\\\a-zA-Z0-9_\x7f-\xff]*)?$/\', $source) > 0',
    "import_namespace(): '$destination' is not a valid namespace name");
  assert('preg_match(\'/^([a-zA-Z_\x7f-\xff][\\\\\\\\a-zA-Z0-9_\x7f-\xff]*)?$/\', $destination) > 0',
    "import_namespace(): '$source' is not a valid namespace name");

  foreach(get_declared_classes() as $class)
    if (strpos($class, $source . '\\') === 0)
      class_alias($class, $destination . ($destination ? '\\' : '') . substr($class, strlen($source . '\\')));

  $functions = get_defined_functions();
  foreach(array_merge($functions['internal'], $functions['user']) as $function)
    if (strpos($function, $source . '\\') === 0)
      function_alias($function, $destination . ($destination ? '\\' : '') . substr($function, strlen($source . '\\')));
}

答案 2 :(得分:1)

我不知道优雅的解决方案,但是......

您可以创建封装函数,将函数封装在外部命名空间中。这将让您保持代码可读性......

function assertThat($x, $y) { return h\assertThat($x, $y); }