0
0
PHPprogramming~5 mins

Aliasing with as keyword in PHP

Choose your learning style9 modes available
Introduction

Aliasing with the as keyword lets you give a shorter or easier name to a class, function, or namespace. This helps you write code that is simpler and clearer.

When you want to use a long or complex namespace but prefer a short name in your code.
When two classes or functions have the same name but come from different places, and you want to avoid confusion.
When you want to make your code easier to read by using simple names instead of full paths.
When importing multiple classes from different namespaces and want to keep names unique.
When you want to rename a class or function temporarily inside a file for clarity.
Syntax
PHP
<?php
use Full\Namespace\ClassName as AliasName;

// Now you can use AliasName instead of the full ClassName
$object = new AliasName();

The as keyword is used after the full name to create the alias.

You can alias classes, functions, or namespaces when importing with use.

Examples
This example creates an alias UserAlias for the class User in a long namespace.
PHP
<?php
use My\Long\Namespace\User as UserAlias;

$user = new UserAlias();
Here, Helper is aliased as LibHelper to make calling its methods easier.
PHP
<?php
use Some\Library\Helper as LibHelper;

LibHelper::doSomething();
You can also alias functions using as to shorten their names.
PHP
<?php
use function Some\Library\processData as process;

process();
Sample Program

This program shows two classes named Dog and Bird in different namespaces. We use as to give each a unique alias so we can use both in the same file without confusion.

PHP
<?php
namespace Animals\Mammals {
    class Dog {
        public function speak() {
            return "Woof!";
        }
    }
}

namespace Animals\Birds {
    class Bird {
        public function speak() {
            return "Chirp!";
        }
    }
}

namespace {
    use Animals\Mammals\Dog as MammalDog;
    use Animals\Birds\Bird as BirdDog;

    $dog1 = new MammalDog();
    $dog2 = new BirdDog();

    echo $dog1->speak() . "\n";
    echo $dog2->speak() . "\n";
}
OutputSuccess
Important Notes

Aliasing helps avoid name conflicts when using multiple libraries or namespaces.

Always choose clear and meaningful alias names to keep your code readable.

Aliasing only affects the current file where you write the use statement.

Summary

Use as to create a short or different name for a class, function, or namespace.

This helps avoid conflicts and makes code easier to read.

Aliasing works only inside the file where you declare it.