PHP 익명 클래스

Sheeraz Gul 2023년6월20일
PHP 익명 클래스

이 자습서는 PHP의 익명 클래스를 교육하고 다양한 코드 예제를 사용하여 이러한 클래스를 만들고 사용하는 방법을 보여줍니다. 또한 PHP에서 익명 클래스를 중첩하는 방법도 배웁니다.

PHP 익명 클래스

이름에서 알 수 있듯이 익명 클래스는 이름이 없는 클래스입니다. PHP 7은 익명 클래스의 기능을 도입했으며 이 클래스는 한 번만 사용할 수 있습니다.

익명 클래스는 해당 클래스의 개체 내부에 정의됩니다. 익명은 특성 확장, 구현 및 사용을 포함하여 일반 클래스가 수행하는 모든 작업을 수행할 수 있습니다. 익명 클래스의 구문은 다음과 같습니다.

$Anonymous_Object=new class {
// Your code here
}

익명 클래스에 대한 간단한 예를 살펴보겠습니다.

<?php
$Anonymous_Object=new class {
    public function Print_Delftstack(){
        echo "Hello, This is delftstack.com";
    }
};
$Anonymous_Object->Print_Delftstack();
?>

위의 코드는 표준 클래스처럼 작동하며 익명 클래스에서 Print_Delftstack() 함수를 호출합니다. 출력 참조:

Hello, This is delftstack.com

익명 클래스가 클래스를 확장하고 인터페이스를 구현하는 또 다른 예를 살펴보겠습니다.

<?php
class Demo_Class{
    public function Print_Delftstack1(){
        echo "This is delftstack from a parent class.<br>";
    }
}

interface Demo_Interface{
    public function Print_Delftstack2();
}

$Anonymous_Object=new class() extends Demo_Class implements Demo_Interface {
    public function Print_Delftstack2(){
        echo "This is delftstack from the parent interface; the method is implemented from Demo_Interface.";
    }
};

$Anonymous_Object->Print_Delftstack1();
$Anonymous_Object->Print_Delftstack2();
?>

위의 코드는 클래스를 확장하고 인터페이스를 구현한 다음 익명 클래스와 함께 해당 메서드를 사용합니다. 출력 참조:

This is delftstack from a parent class.
This is delftstack from the parent interface; the method is implemented from Demo_Interface.

익명 클래스가 어떻게 작동하는지 알 수 있듯이 클래스가 내부 사용에서 어떻게 익명으로 작동할 수 있습니까? 이에 대한 대답은 PHP가 익명 클래스에 고유한 이름을 부여하는 것입니다. 익명 클래스의 이름을 알아봅시다:

<?php
var_dump(get_class(new class() {
    public function Print_Delftstack(){
        echo "Hello, This is delftstack.com";
    }
} ));
?>

위의 코드는 익명 클래스의 고유한 이름인 주어진 익명 클래스에 대한 정보를 덤프합니다. 출력을 참조하십시오.

string(46) "class@anonymousC:\Apache24\htdocs\new.php:2$5" 

PHP의 중첩된 익명 클래스

익명은 다른 클래스의 메서드 본문 내부에 중첩될 수 있지만 외부 클래스의 protectedprivate 멤버에 액세스할 수 없습니다. 예를 들어 보겠습니다.

<?php
class Demo_Class{
   public function Delftstack1(){
      return new class(){
         public function Delftstack2(){
            echo "This is delftstack two methods from the nested anonymous class.";
         }
      };
   }
}

$Demo_Object=new Demo_Class();
$Demo_Object->Delftstack1()->Delftstack2();
?>

위의 코드는 표준 클래스에 중첩된 익명 클래스를 구현하는 방법을 보여줍니다. 출력을 참조하십시오.

This is delftstack two methods from the nested anonymous class.
작가: Sheeraz Gul
Sheeraz Gul avatar Sheeraz Gul avatar

Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.

LinkedIn Facebook

관련 문장 - PHP Class