Why use the "use" keyword in PHP to import core identifiers?
Asked Answered
L

2

8

Sometimes in some libraries like thephpleague/csv, I see the use keyword to import core identifiers (e.g. functions, classes or constants) but I can't understand why they are being imported at all.

See the following example:

use Generator;
use SplFileObject;
use function filter_var;
use function get_class;
use function mb_strlen;
use function rawurlencode;
use function sprintf;
use function str_replace;
use function str_split;
use function strcspn;
use function strlen;
use const FILTER_FLAG_STRIP_HIGH;
use const FILTER_FLAG_STRIP_LOW;
use const FILTER_SANITIZE_STRING;

Or more from here.

These classes, functions and constants that are imported in this file are belong to PHP core, so we wouldn't actually need to import them.

Why this and other libraries import these?

Lindgren answered 8/8, 2021 at 8:40 Comment(0)
A
8

The objective with this is to perform a (micro) performance optimization, as described here. (Archived link, just in case).

The idea being that by using avoiding the global name lookup and skipping the fall-back rules, some performance can be gained.

Note that with any real-life workload these gains are negligible and inconsequential, and they are mostly made irrelevant by opcode caching. Nevertheless, the performance gain, minute as it may be, exists.

You can read some lengthy and interesting discussion about this:

Auriscope answered 10/8, 2021 at 10:40 Comment(0)
M
3

When you're in a namespace, every bare name refers to a name within that namespace. I.e.:

namespace Foo;

echo bar();

bar here really means Foo\bar.

There are rules for fallbacks to global names if the name doesn't exist within this namespace. If you don't want to rely on those rules, or if you do actually have those names defined in your namespace and you don't want to have to constantly write \bar() explicitly, that's when you may explicitly use those global names to make it unambiguous that bar refers to \bar and not Foo\bar.

It's probably not necessary most of the time for PHP builtin names, but perhaps the project author has simply established that as a rule to avoid bugs due to namespace resolution ambiguity.

Moisten answered 8/8, 2021 at 8:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.