In PHP Use is More Like an Alias than an Import

PHP Use is an Alias

PHP has a use statement that allows the importing or, more accurately, aliasing of classes into the current namespace.

In other languages, like Python, importing a nonexistent class or module will fail at the import.

>>> import doesnotexist
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named doesnotexist

In PHP, this doesn’t happen, instead the program will fail later when the aliased class, function, or constant is is actually used.

<?php

use Does\Not\Exist;
use function Does\Not\Exist\nope;
use const Does\Not\Exist\AT_ALL;

new Exist(); // Uncaught Error: Class 'Does\Not\Exist' not found
nope(); // Call to undefined function Does\Not\Exist\nope()
echo AT_ALL; // Use of undefined constant AT_ALL - assumed 'AT_ALL'

This can be unexpected or tricky behavior if one is used to a compiler or interpreter indicating an import failed. So think of PHP’s use as more like aliasing and less like a typical import.

Good old tests can help catch errors like these. So can static analysis tools like phpstan or psalm.

Posted in PHP