PHP匿名クラス

Sheeraz Gul 2023年6月20日
PHP匿名クラス

このチュートリアルでは、PHP の匿名クラスについて学習し、さまざまなコード例を使用してこれらのクラスを作成および使用する方法を示します。 また、PHP で無名クラスをネストする方法も学びます。

PHP匿名クラス

名前が示すように、無名クラスは名前を持たないクラスです。 PHP 7 で匿名クラスの機能が導入されました。このクラスは 1 回限りの使用を目的としています。

匿名クラスは、そのクラスのオブジェクト内で定義されます。 匿名は、通常のクラスが実行するすべてのことを実行できます。これには、特性の拡張、実装、および使用が含まれます。 匿名クラスの構文は次のとおりです。

$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 のネストされた匿名クラス

匿名は、別のクラスのメソッドの本体内にネストできますが、外部クラスの protected および private メンバーにアクセスすることはできません。 例を試してみましょう:

<?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