Giới thiệu
Interface là một tính năng quan trọng của lập trình hướng đối tượng, cho phép chỉ định các phương thức phải được triển khai bởi một lớp, mà không cần định nghĩa cách thức triển khai.
PHP hỗ trợ interface qua từ khóa interface. Interface tương tự như class nhưng chỉ chứa phương thức không có thân hàm (method body). Các phương thức trong interface phải là public. Lớp con triển khai các phương thức này phải dùng từ khóa implements thay vì extends, và phải cung cấp triển khai cho tất cả phương thức trong interface cha.
Cú pháp cơ bản
<?php
interface testinterface {
public function testmethod();
}
class testclass implements testinterface {
public function testmethod() {
echo "implements interface method";
}
}
?>
Nếu lớp triển khai không định nghĩa tất cả phương thức từ interface, PHP sẽ ném ngoại lệ (exception).
Ví dụ: Thiếu triển khai phương thức
<?php
interface testinterface {
public function test1();
public function test2();
}
class testclass implements testinterface {
public function test1() {
echo "implements interface method";
}
}
$obj = new testclass();
?>
Lỗi
PHP Fatal error: Class testclass contains 1 abstract method and must therefore be declared abstract or implement the remaining methods (testinterface::test2)
Interface có thể kế thừa (Extendable interface)
Giống như class thông thường, interface cũng có thể kế thừa từ interface khác bằng từ khóa extends.
<?php
interface testinterface {
public function test1();
}
interface myinterface extends testinterface {
public function test2();
}
class testclass implements myinterface {
public function test1() {
echo "implements test1 method";
}
public function test2() {
echo "implements test2 method";
}
}
?>
Đa kế thừa (Multiple inheritance) qua Interface
PHP không cho phép một class extends nhiều class cha. Tuy nhiên, đa kế thừa có thể đạt được bằng cách cho class con implements một hoặc nhiều interface.
<?php
interface testinterface {
public function test1();
}
class testclass {
public function test2() {
echo "this is test2 function in parent class\n";
}
}
class myclass extends testclass implements testinterface {
public function test1() {
echo "implements test1 method\n";
}
}
$obj = new myclass();
$obj->test1();
$obj->test2();
?>
Kết quả
implements test1 method this is test2 function in parent class
Ví dụ thực tế: Hình học
<?php
interface shape {
public function area();
}
class circle implements shape {
private $rad;
public function __construct() {
$this->rad = 5;
}
public function area() {
echo "area of circle=" . M_PI * pow($this->rad, 2) . "\n";
}
}
class rectangle implements shape {
private $width;
private $height;
public function __construct() {
$this->width = 20;
$this->height = 10;
}
public function area() {
echo "area of rectangle=" . $this->width * $this->height . "\n";
}
}
$c = new circle();
$c->area();
$r = new rectangle();
$r->area();
?>
Kết quả
area of circle=78.539816339745 area of rectangle=200