Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> PHP

Aliasing/Importing Namespaces ใน PHP

บทนำ

คุณสมบัติสำคัญของ Namespaces คือการอ้างอิง Fully Qualified Name ด้วย Alias (ชื่อ مستعار) หรือ Importing PHP รองรับ:

  • Aliasing Class Name
  • Aliasing Interface Name
  • Aliasing Namespace Name
  • Aliasing/Importing Function และ Constant Names

ใช้ Operator use สำหรับ Aliasing

ตัวอย่าง use Operator

<?php
// test1.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;
// hello() ตอนนี้หมายถึง mynewspace\sayhello
?>

ผลลัพธ์

Hello from mynamespace
Hello from my new space

รวม Multiple Use Statements (PHP 7+)

<?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();
?>

ผลลัพธ์

myclass in mynamespace
testclass in mynamespace

Importing และ 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;  // Dynamic - ใช้ Imported Name
?>

ข้อจำกัดสำคัญของ use

  • ต้องอยู่ใน Global Scope หรือ Namespace Scope - ไม่สามารถอยู่ใน Function/Block ได้
  • Compile Time - Import เกิดขึ้นตอน Compile ไม่ใช่ Runtime
  • Per-file Basis - Included Files ไม่สืบทอด Import Rules

ตัวอย่างผิด (Illegal)

<?php
function myfunction() {
    use myspace\myclass;  // Fatal Error: use ไม่อยู่ใน Global/Namespace Scope
}
?>

Group Use Declarations (PHP 7+)

<?php
use App\Controller\{UserController, PostController, CommentController};
use function App\Helper\{formatDate, formatTime, sanitize};
use const App\Config\{MAX_USERS, DEFAULT_LANG, TIMEZONE};
?>

Best Practices

  • ใช้ Fully Qualified Names ใน use (ขึ้นต้น \) เพื่อความชัดเจน
  • Group Use Declarations เพื่อลดโค้ดซ้ำ
  • ใช้ Alias (as) เมื่อชื่อชนกัน
  • Import เฉพาะที่จำเป็น - หลีกเลี่ยง Import ทั้ง Namespace