PHP Aliasing/Importing namespaces

In PHP, namespaces support aliasing and importing to simplify references to fully qualified names. You can alias class names, interface names, namespace names, and function/constant names using the use operator.

Basic Aliasing with use Operator

The use operator allows you to create aliases for namespaced elements −

<?php
namespace mynamespace;
function sayhello(){
    echo "Hello from mynamespace<br>";
}
sayhello();

namespace mynewspace;
function sayhello(){
    echo "Hello from my new space<br>";
}
sayhello();
use mynewspace\sayhello as hello;
?>
Hello from mynamespace
Hello from my new space

Multiple use Statements

You can import multiple classes or functions in a single use statement −

<?php
namespace mynamespace;
class myclass{
    function test() { echo "myclass in mynamespace<br>"; }
}
class testclass{
    static function test() { echo "testclass in mynamespace<br>"; }
}
use mynamespace\myclass as myclass, mynamespace\testclass;
$a = new myclass();
$a->test();
$b = new testclass();
$b->test();
?>
myclass in mynamespace
testclass in mynamespace

Dynamic Class Names with Imports

You can substitute imported class names dynamically using variables −

<?php
namespace mynamespace;
class myclass{
    function test() { echo "myclass in mynamespace<br>"; }
}
use mynamespace\myclass as myclass;
$a = new myclass();
$b = 'myclass';
$c = new $b();
$c->test();
?>
myclass in mynamespace

Important Rules

The use keyword has specific scope limitations:

  • Must be declared in the global scope or inside namespace declarations
  • Cannot be used inside functions or blocks
  • Importing happens at compile time, not runtime
  • Each file has its own importing rules − included files don't inherit them
<?php
// This is ILLEGAL
function myfunction(){
    use myspace\myclass;  // Error: use statements not allowed here
}
?>

Conclusion

PHP namespace aliasing with the use operator simplifies code by creating shorter references to fully qualified names. Remember that use statements must be at global or namespace scope and work on a per-file basis.

Updated on: 2026-03-15T09:12:05+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements