DEV Community

spO0q
spO0q

Posted on

Understanding PHP aliases

You might not know that PHP allows creating aliases in various ways.

Why use class aliases?

class_alias is pretty straighforward:

class MyClass {}
class_alias('MyClass', 'MyAlias');
$obj = new MyAlias();
Enter fullscreen mode Exit fullscreen mode

Source: PHP doc - class-alias

You can use it to handle multiple versions of the same apps and manage deprecations.

If you maintain a library and want to modify the namespaces or refactor entire parts of the code, it can be nice to avoid bad breaking changes.

These are definitely not the only usages, but you might need it.

class_alias vs. use

Imports are a bit different and rely on the use keyword:

use MyClass as AnotherClassName;
use function myFunction as myFunctionAlias;
Enter fullscreen mode Exit fullscreen mode

It works with various structures, like constants, functions, classes, interfaces, traits, enums and namespaces.

Source: PHP doc - importing

It's a great feature that sometimes allows better readability and prevents bad collisions.

Inbuilt aliases

Some PHP functions can be called with multiple names. Here is the list.

The main reason is backward compatibility, and the core team discourages similar usages in custom scripts, but it's sometimes necessary.

The big caveat and a few warnings

Aliases can be convenient but should be used sparingly. Otherwise, it might create more problems than it solves (less readability, confusions).

If you are doing imports with the use keyword, be careful, especially if you include other files.

These files won't inherit the parent imports automagically, which could result in fatal errors if you try to call some utility you have imported in your parent script.

It's a typical issue you might struggle to solve, so be aware of that rule.

Can we alias a variable?

Yes, and it's called a reference:

$a = "freeze";
$b = &$a;
Enter fullscreen mode Exit fullscreen mode

Source: PHP doc - references explained

The & symbol is used to explicitly create such reference.

N.B.: Note that, due to the way PHP stores objects in memory, it's not exacly the same for this particular type.

Top comments (0)