Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> PHP

Sử dụng Namespace (Using Namespaces) trong PHP

Giới thiệu

Class, function hoặc constant trong namespace có thể được sử dụng theo các cách sau:

  • Sử dụng class trong namespace hiện tại
  • Chỉ định namespace tương đối so với namespace hiện tại
  • Đưa ra tên namespace đầy đủ (fully qualified name)

Từ namespace hiện tại

Trong ví dụ này, namespace được nạp từ test1.php. Tên function/class được tham chiếu không có namespace sẽ truy cập những thứ trong namespace hiện tại.

File test1.php

#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"; }
}
?>

Sử dụng trong file khác

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

Kết quả

hello in myspace
hello in myspace
200

Sử dụng namespace tương đối (Relative namespace)

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

Kết quả

hello in space1
hello in space1
100

Namespace đầy đủ (Fully qualified namespace)

Function và class được cho tên namespace tuyệt đối:

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

Kết quả

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