Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to alias a function in PHP?

Is it possible to alias a function with a different name in PHP? Suppose we have a function with the name sleep. Is there a way to make an alias called wait?

By now I'm doing like this:

function wait( $seconds ) {     sleep($seconds); } 
like image 730
Atif Avatar asked Nov 06 '09 16:11

Atif


People also ask

How to use alias in PHP?

The ability to refer to an external fully qualified name with an alias, or importing, is an important feature of namespaces. This is similar to the ability of unix-based filesystems to create symbolic links to a file or to a directory. PHP can alias(/import) constants, functions, classes, interfaces, and namespaces.

How to give alias name in PHP?

PHP | class_alias() Function The class_alias() function is an inbuilt function in PHP which is used to create an alias name of the class. The functionality of the aliased class is similar to the original class.

What is a function alias?

From OSP dictionary we would define Function alias as the rules that promote the usage of the function (Java/SQL) to the users (non-developers ) who maintain business rules (Decision tree, Decision table, When) or create/configure reports in Production.

How do you call a function in PHP?

There are two methods for doing this. One is directly calling function by variable name using bracket and parameters and the other is by using call_user_func() Function but in both method variable name is to be used. call_user_func( $var );


2 Answers

Until PHP 5.5

yup, function wait ($seconds) { sleep($seconds); } is the way to go. But if you are worried about having to change wait() should you change the number of parameters for sleep() then you might want to do the following instead:

function wait() {    return call_user_func_array("sleep", func_get_args()); } 
like image 170
Lukman Avatar answered Oct 15 '22 14:10

Lukman


PHP 5.6+ only

Starting with PHP 5.6 it is possible to alias a function by importing it:

use function sleep as wait; 

There's also an example in the documentation (see "aliasing a function").

like image 31
Jon Avatar answered Oct 15 '22 14:10

Jon