Giới thiệu
Như tên gọi, lớp ẩn danh (anonymous class) là lớp không có tên. Nó dành cho việc sử dụng một lần, khi cần định nghĩa lớp "ngay lập tức" (on the fly). Tính năng này được giới thiệu từ PHP 7.
Định nghĩa lớp ẩn danh nằm bên trong một expression mà kết quả là một đối tượng của lớp đó. Nó được định nghĩa với cú pháp new class như sau:
Cú pháp
<?php
$obj = new class {
public function sayhello() {
echo "Hello World";
}
};
$obj->sayhello();
?>
Lớp ẩn danh có thể làm mọi thứ mà lớp thông thường làm: kế thừa class khác, implements interface, sử dụng trait.
Ví dụ: Kế thừa và implements interface
<?php
class parentclass {
public function test1() {
echo "test1 method in parent class\n";
}
}
interface parentinterface {
public function test2();
}
$obj = new class() extends parentclass implements parentinterface {
public function test2() {
echo "implements test2 method from interface";
}
};
$obj->test1();
$obj->test2();
?>
Kết quả
test1 method in parent class implements test2 method from interface
Lớp ẩn danh lồng nhau (Nested anonymous class)
Lớp ẩn danh có thể được lồng bên trong thân phương thức của lớp khác. Tuy nhiên, đối tượng của nó không có quyền truy cập vào thành viên private hoặc protected của lớp bên ngoài.
<?php
class testclass {
public function test1() {
return new class() {
public function test2() {
echo "test2 method of nested anonymous class";
}
};
}
}
$obj2 = new testclass();
$obj2->test1()->test2();
?>
Kết quả
test2 method of nested anonymous class
Tên nội bộ của lớp ẩn danh
PHP parser cấp một tên duy nhất cho lớp ẩn danh để sử dụng nội bộ:
<?php
var_dump(get_class(new class() {}));
?>
Kết quả
string(60) "class@anonymous/home/cg/root/1569997/main.php0x7f1ba68da026"