Namespace คือ เส้นทางหรือตำแหน่งที่คลาสนั้นถูกเก็บอยู่ เป็นการเเยกหมวดหมู่หรือเก็บประเภทเดียวกันไว้ด้วยกัน เพื่อง่ายต่อการจดจำและสะดวกต่อการใช้งาน และยังแก้ปัญหาการตั้งคลาสซ้ำกัน
การนำ namespace อื่นเข้ามาใช้
กรณีเราต้องนำคลาสจาก namespace อื่นๆ เข้ามาใช้ใน namespace นี้ จะใช้คำสั่ง use เรียกเข้ามา และใช้คำสั่ง as เพื่อตั้งชื่อเล่นให้ สะดวกต่อการเรียกใช้งาน
ตัวอย่างการสร้างและ เรียกใช้ namespece
<?php
namespace mindphp\sample1\event; //กำหนดชื่อ
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class listener implements EventSubscriberInterface
{
static public function getSubscribedEvents() {
return array(
'core.page_header' => 'page_header',
'core.user_setup' => 'load_language_on_setup',
);//เรียกใช้ event จากที่มีให้ใน phpbb
}
protected $halper;
protected $template;
public function __construct( \phpbb\controller\helper $halper , \phpbb\template\template $template){
$this->halper = $halper;
$this->template = $template;
}//กำหนดตัวแปร construct
public function page_header($event) {
$this->template->assign_vars(array(
'U_MINDPHP_SAMPLE1_PAGE' => $this->halper->route('sample1_controller', array('name' => 'mindphp')),
));
}
public function load_language_on_setup($event) { // function สำหรับเรียกงานภาษา
$lang_set_ext = $event['lang_set_ext'];
$lang_set_ext[] = array(
'ext_name' => 'mindphp/sample1',
'lang_set' => 'sample1',
);
$event['lang_set_ext'] = $lang_set_ext;
}
}
ดูต่อและคำอธิบายโค้ดที่นี่