Giới thiệu
Một tính năng quan trọng của namespace là khả năng tham chiếu đến tên fully qualified bên ngoài bằng một bí danh (alias), hay importing. PHP namespace hỗ trợ các loại aliasing/importing sau:
- aliasing tên class
- aliasing tên interface
- aliasing tên namespace
- aliasing hoặc importing tên function và constant
Trong PHP, aliasing thực hiện bằng toán tử use.
Toán tử use
#test1.php
<?php
namespace mynamespace;
function sayhello() { echo "Hello from mynamespace\n"; }
sayhello();
namespace mynewspace;
function sayhello() { echo "Hello from my new space\n"; }
sayhello();
use \mynewspace\sayhello as hello;
?>
Kết quả
Hello from mynamespace Hello from my new space
Kết hợp nhiều use statements
<?php
namespace mynamespace;
class myclass {
function test() { echo "myclass in mynamespace\n"; }
}
class testclass {
static function test() { echo "testclass in mynamespace\n"; }
}
use \mynamespace\myclass as myclass, \mynamespace\testclass;
$a = new myclass();
$a->test();
$b = new \mynamespace\testclass();
$b->test();
?>
Kết quả
myclass in mynamespace testclass in mynamespace
Importing và tên động (Dynamic names)
<?php
namespace mynamespace;
class myclass {
function test() { echo "myclass in mynamespace\n"; }
}
class testclass {
static function test() { echo "testclass in mynamespace\n"; }
}
use \mynamespace\myclass as myclass;
$a = new myclass;
$b = 'myclass';
$c = new $b;
?>
Từ khóa use phải được khai báo ở phạm vi outermost (ngoài cùng) hoặc global scope, hoặc bên trong khai báo namespace. Quá trình importing diễn ra tại compile time, không phải runtime. Do đó không thể block-scoped. Cách dùng sau sẽ bất hợp pháp:
<?php
function myfunction() {
use myspace\myclass; // Illegal!
}
?>
File include sẽ KHÔNG kế thừa quy tắc importing của file cha vì chúng hoạt động trên cơ sở per-file.