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

Khai báo Namespace trong PHP

Giới thiệu

Khai báo class, function và constant bên trong namespace ảnh hưởng đến quyền truy cập của chúng, mặc dù bất kỳ code PHP nào khác cũng có thể có mặt trong đó. Từ khóa namespace của PHP dùng để khai báo namespace mới. File .php phải có khai báo namespace ở dòng đầu tiên ngay sau thẻ <?php, trước bất kỳ code nào khác như HTML script.

Ví dụ đúng

<?php
namespace myspace;
class myclass { /* ... */ }
function hello() { echo "Hello World\n"; }
?>

Nếu khai báo namespace không ở đầu file, PHP parser ném fatal error:

Ví dụ sai

<html>
<body> Hello world
<?php
namespace myspace;
function hello() { echo "Hello World\n"; }
use myspace;
myspace\hello();
?>
</body>
</html>

Lỗi

PHP Fatal error: Namespace declaration statement has to be the very first statement or after any declare call in the script

Chỉ cấu trúc declare có thể xuất hiện trước khai báo namespace:

<?php
declare (strict_types=1);
namespace myspace;
function hello() { echo "Hello World\n"; }
use myspace;
myspace\hello();
?>