Artem Chernov
Artem Chernov

Reputation: 906

What is the "use function" expression?

I saw this snippet and I dont understand why used use function array_map expression ?

<?php

namespace Project\MyProject;

use function array_map;

class MyProjectClass 
{
    protected $arr = [];
    public function __construct(array $arr)
    {
        $this->arr = array_map('trim', $arr);
    }
}

Upvotes: 3

Views: 1636

Answers (1)

mario
mario

Reputation: 145512

As mentioned in how to call global functions classes from namespace PHP:

use function array_map;

aliases a global function into the local namespace.

  • This is generally unneeded.
  • PHP looks up functions in the global scope anyway.
  • It only makes sense if you were to redeclare a global function in the current namespace.
    • Which is somewhat of a rare situation.
    • But if you had (this is called "monkey patching") then you also wouldn't want to undermine it with use function.

The real reason use function was introduced is:

  • For actually aliasing / renaming functions:

    • use function App\Helpers\my_mappymcmapface as array_map;
    • use function \trim as chomp;
  • And also because PHP coders have been littering their codebases with \trim and \strpos before.

    • That was one of those unwarranted micro-performance optimizations.

So yes, for this case it's pointless decoration.

Upvotes: 7

Related Questions