PHP Aliasing/Importing namespaces


Introduction

An important feature of namespaces is the ability to refer to an external fully qualified name with an alias, or importing. PHP namespaces support following kinds of aliasing or importing −

  • aliasing a class name,
  • aliasing an interface name,
  • aliasing a namespace name
  • aliasing or importing function and constant names.

In PHP, aliasing is accomplished with the use operator.

use operator

Example

 Live Demo

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

Output

Hello from mynamespace
Hello from my new space

multiple use statements combined

Example

 Live Demo

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

Output

myclass in mynamespace
testclass in mynamespace

Importing and dynamic names

substitute name of imported class dynamically

Example

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

The use keyword must be declared in the outermost or the global scope, or inside namespace declarations. Process ofimporting is done at compile time and not runtime. Therefore it cannot be block scoped. Following usage will be illegal

Example

<?php
function myfunction(){
   use myspace\myclass;
   //
   //
}
?>

Included files will NOT inherit the parent file's importing rules as they are per file basis

Updated on: 18-Sep-2020

651 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements