소개
이름에서 알 수 있듯이 익명 클래스는 이름이 없는 클래스입니다. 이것은 한 번 사용하기 위한 것이며 클래스를 즉석에서 정의해야 하는 경우입니다. 익명 클래스의 기능은 PHP 7 버전부터 도입되었습니다.
익명 클래스의 정의는 결과가 해당 클래스의 객체인 표현식 내부에 있습니다. 새 클래스로 정의됩니다. 다음과 같은 구문
구문
<?php
$obj=new class {
public function sayhello(){
echo "Hello World";
}
};
$obj->sayhello();
?> 익명 클래스는 다른 클래스를 확장하거나 인터페이스를 구현하거나 특성을 사용하는 등 일반적인 작업을 수행할 수 있습니다.
다음 코드에서 익명 클래스는 parentclass를 확장하고 parentinterface를 구현합니다.
예시
<?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();
?> 출력
출력은 아래와 같습니다 -
test1 method in parent class implements test2 method from interface
중첩된 익명 클래스
익명 클래스는 다른 클래스 메소드의 본문 내부에 중첩될 수 있습니다. 그러나 해당 개체는 외부 클래스의 private 또는 protected 멤버에 액세스할 수 없습니다.
예시
<?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();
?> 출력
위의 코드는 다음 결과를 생성합니다 -
test2 method of nested anonymous class
익명 클래스의 내부 이름
PHP 파서는 내부 사용을 위해 익명 클래스에 고유한 이름을 부여합니다.
예시
<?php
var_dump(get_class(new class() {} ));
?> 출력
이것은 다음과 유사한 출력을 생성합니다 -
string(60) "class@anonymous/home/cg/root/1569997/main.php0x7f1ba68da026"