Alias ​​class method as a global function

Can a class method be used as a global function?

I have a class that acts as a wrapper around gettext functions in PHP. I have a function called _t() that deals with translations.

I would like to be able to call it _t() from anywhere in my code without having to do it through an instance of the object ( $translate::_t() ), as this seems rather cumbersome.

I was thinking about using namespaces to give the object an alias:

 Use translations\TranslationClass as T 

Although this is the best improvement: T::_t() . this is still not as necessary as just doing _t() .

Are there anyways for the alias T::_t() as soon as _t() for the entire application?

+4
source share
2 answers

You can create a wrapper function or use create_function ().

 function _t() { call_user_func_array(array('TranslationClass', '_t'), func_get_arts()); } 

Or you can create a function on the fly:

 $t = create_function('$string', 'return TranslationClass::_t($string);'); // Which would be used as: print $t('Hello, World'); 
+2
source

You can use the eval () function to convert methods as global functions.

 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); } 

This example works well with static methods.

0
source

All Articles