As a follow on to my short post about namespaces and functions from a year ago I thought it would be worth covering importing a specific function and aliasing functions via namespace operators too. This has been possible since PHP 5.6, but there is a nice addition in PHP 7 I’ll cover towards the end.

In the previous article I demonstrated how you can namespace functions and use them, but as a refresher; you can enclose functions within a namespace just like a class. In the following example there is a function setup in the MyProject\MyModule namespace first, which is subsequently called by code inside the root namespace (namespace { }).

Hopefully this is all pretty straight forward and clear to follow. Now onto the use keyword and how it can be implemented to import a specific function.

Note the use function construct here instead of the usual straight forward use that you’d normally see when importing a PHP namespace. This imports just the specified function for use in the current scope.

So, my example function name sure is a little ungainly and a bit of a chore to type with it’s long name. For the sake of demonstration let’s assume that we can’t change the function name, but we still want it to be shorter in our current scope. To do this we can use the familiar as keyword used in namespace aliasing.

As we did earlier we’ve gone with use function to show that we’re importing and later aliasing a particular function. This is also works for functions in the root or same namespace as each other.

Now if you’re running PHP 7 you can do a another little trick with the namespace operators. If you want to include multiple specific functions in the current scope you can use the new braced grouping syntax.

Here you can see group syntax ({verb,when}) and function aliasing that we saw earlier working together to create the expected text output.

Unfortunately, you cannot alias and group import in the one hit as you would generate a parse error (syntax error, unexpected 'as' (T_AS), expecting ';') with code like the following example:

So more recent additions to PHP give namespaces more power than previously discussed with the ability to import a specific function being the highlight.