วันอังคารที่ 21 ธันวาคม พ.ศ. 2553

การสร้าง interface ในภาษา php

การสร้าง interface ในภาษา php
interface คล้ายกับคลาสแต่ไม่มีการ implement method เหมือนเป็นคลาสที่ประกาศว่ามี method อะไรบ้างแต่ไม่เขียนการทำงานของ method

ตัวอย่าง<?php
interface interfaceTest{
public function t();
}
class test implements interfaceTest
{
public function t(){
echo "implement interface";
}
}
$obj=new test;
$obj->t();
?>
การสร้าง interface จะใช้คำว่า interface นำหน้าจากตัวอย่างเป็นการ interface ชื่อ interfaceTest ซึ่งมี method ชื่อ t ประกาศไว้
โดย interface จะไม่มีการเขียนการทำงานของ method ใน interface
เมื่อ class นำ interface ไปใช้ต้อง implement ทุก method ที่ประกาศไว้ใน interface
ถ้า implement ไม่ครบจะเกิด error
การ implement interface ใช้คำว่า implements ดังตัวอย่าง

ไม่มีความคิดเห็น:

แสดงความคิดเห็น