Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the "use function" expression?

Tags:

php

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);
    }
}
like image 243
Artem Chernov Avatar asked Mar 08 '26 02:03

Artem Chernov


1 Answers

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.

like image 89
mario Avatar answered Mar 09 '26 15:03

mario



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!