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

การใช้ Namespaces ใน PHP

บทนำ

Class, Function หรือ Constant ใน Namespace สามารถใช้ได้ 3 วิธี:

  • ใช้ใน Current Namespace
  • ระบุ Namespace แบบ Relative (สัมพัทธ์)
  • ระบุ Fully Qualified Name (ชื่อเต็ม)

1. ใช้จาก Current Namespace

Function/Class ที่อ้างอิงโดยไม่มี Namespace จะเข้าถึงใน Current Namespace

ไฟล์ test1.php

<?php
namespace myspace\space1;
const MAX = 100;
function hello() { echo "hello in space1\n"; }
class myclass {
    static function hellomethod() { echo "hello in space1\n"; }
}
?>

ไฟล์หลัก

<?php
namespace myspace;
include 'test1.php';
const MAX = 200;
function hello() { echo "hello in myspace\n"; }
class myclass {
    static function hellomethod() { echo "hello in myspace\n"; }
}

hello();
myclass::hellomethod();
echo MAX;
?>

ผลลัพธ์

hello in myspace
hello in myspace
200

2. ใช้ Relative Namespace

เข้าถึงด้วย Namespace แบบ Relative:

<?php
namespace myspace;
include 'test1.php';
const MAX = 200;
function hello() { echo "hello in myspace\n"; }
class myclass {
    static function hellomethod() { echo "hello in myspace\n"; }
}

space1\hello();
space1\myclass::hellomethod();
echo space1\MAX;
?>

ผลลัพธ์

hello in space1
hello in space1
100

3. Fully Qualified Namespace

ใช้ Absolute Namespace Name (ขึ้นต้นด้วย \):

<?php
namespace myspace;
include 'test1.php';
const MAX = 200;
function hello() { echo "hello in myspace\n"; }
class myclass {
    static function hellomethod() { echo "hello in myspace\n"; }
}

\myspace\hello();
\myspace\space1\hello();
\myspace\myclass::hellomethod();
\myspace\space1\myclass::hellomethod();
echo \myspace\MAX . "\n";
echo \myspace\space1\MAX;
?>

ผลลัพธ์

hello in myspace
hello in space1
hello in myspace
hello in space1
200
100

สรุปการเข้าถึง

รูปแบบตัวอย่างความหมาย
Unqualifiedhello()Current Namespace
Qualifiedspace1\hello()Relative to Current Namespace
Fully Qualified\myspace\space1\hello()Absolute Global Namespace

คำสั่ง use (Importing)

ใช้ use เพื่อ Import Class/Function/Constant:

<?php
namespace myspace;
use myspace\space1\myclass as MyClass;
use function myspace\space1\hello;
use const myspace\space1\MAX;

$obj = new MyClass();
hello();
echo MAX;
?>