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

การประกาศ Namespace ใน PHP

บทนำ

การประกาศ Class/Function/Constants ภายใน Namespace ส่งผลต่อการเข้าถึง PHP ใช้คีย์เวิร์ด namespace ประกาศ Namespace ใหม่ ไฟล์ .php ต้องมี Namespace Declaration ในบรรทัดแรกหลัง <?php ก่อนโค้ดอื่นๆ (รวม HTML)

ตัวอย่างที่ถูกต้อง

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

ตัวอย่างผิด: Namespace ไม่อยู่บนสุด

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

ผลลัพธ์ (Error)

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

เฉพาะ declare เท่านั้นที่อยู่ก่อน namespace ได้

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

ข้อสังเกต

  • Namespace Declaration ต้องเป็น Statement แรก (หรือหลัง declare)
  • HTML/Whitespace/Output ก่อน Namespace Declaration = Error
  • Bracketed Syntax ยกเว้นกฎนี้ได้ (แต่ไม่แนะนำ)
  • ไฟล์ที่ Include เข้ามา ไม่ได้รับผลกระทบจาก Namespace ของไฟล์หลัก

Best Practice

  • 1 File = 1 Namespace = 1 Class (PSR-4)
  • Namespace Declaration บรรทัดแรกเสมอ
  • ใช้ Composer Autoloading แทน Manual Include