Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/271.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 别名类方法作为全局函数_Php_Methods_Alias - Fatal编程技术网

Php 别名类方法作为全局函数

Php 别名类方法作为全局函数,php,methods,alias,Php,Methods,Alias,是否可以将类方法别名为全局函数 我有一个类,它充当PHP中gettext函数的包装器。我有一个名为\u t()的函数,它处理翻译 我希望能够在代码中的任何地方将其称为\u t(),而不必通过实例化对象($translate::\u t())来执行,因为这看起来相当笨拙 我考虑使用名称空间为对象提供别名: Use translations\TranslationClass as T 虽然这是一个更好的改进:T::\u T()。它仍然不像只需要做\u t()那样需要 有没有办法在整个应用程序中将T

是否可以将类方法别名为全局函数

我有一个类,它充当PHP中gettext函数的包装器。我有一个名为
\u t()
的函数,它处理翻译

我希望能够在代码中的任何地方将其称为
\u t()
,而不必通过实例化对象(
$translate::\u t()
)来执行,因为这看起来相当笨拙

我考虑使用名称空间为对象提供别名:

Use translations\TranslationClass as T
虽然这是一个更好的改进:
T::\u T()
。它仍然不像只需要做
\u t()
那样需要


有没有办法在整个应用程序中将
T::\u T()
别名为
\u T()

或者,您可以动态创建一个函数:

$t = create_function('$string', 'return TranslationClass::_t($string);');

// Which would be used as:
print $t('Hello, World');
可以使用eval()函数将方法转换为全局函数

function to_procedural($classname, $method, $alias)
{
  if (! function_exists($alias))
  {
   $com  = $command = "function ".$alias."() { ";
   $com .= "\$args = func_get_args(); ";
   $com .= "return call_user_func_array(array(\"".$classname."\", \"".$method."\"), \$args); }";
   @eval($command);
  }
  return function_exists($alias);
}

这个例子很适合静态方法。

很有趣。我将对此进行调查,并在一天左右回来:)第二种方法很棘手。我们有美元符号前缀,它通常被认为是变量,在我们有圆括号之后,我们将变量作为函数调用。我认为这会带来很多混乱、混乱和维护问题,不,这取决于你如何看待它。我将变量视为指向各种数据类型(包括函数)的指针。考虑可调用数组:$x= [$ObjeTrf,'ObjutTrime]);调用$x()将调用$objectRef->objectMethod();。这是一个完全有效的结构。大多数语言都支持函数指针的概念。这次性能如何?使用eval()会有任何巨大的性能影响吗?
function to_procedural($classname, $method, $alias)
{
  if (! function_exists($alias))
  {
   $com  = $command = "function ".$alias."() { ";
   $com .= "\$args = func_get_args(); ";
   $com .= "return call_user_func_array(array(\"".$classname."\", \"".$method."\"), \$args); }";
   @eval($command);
  }
  return function_exists($alias);
}