PHP

Anonymous Classes in PHP

The following article describes Anonymous Classes in PHP.

Basically, an anonymous class in PHP is a class that doesn’t have a name, and it can be created and instantiated in a single line of code. Anonymous classes are useful when you need to create a one-off instance of a class, for example, to pass to a function as an argument or to store in a variable.

Here’s an example of how to create and use an anonymous class in PHP:

<?php
    $x=new class{
            function f1()
            {
                echo 'Inside the function f1()...<br>';
            }
    };
    $x->f1();
?>

Output

Example of Anonymous Classes in PHP
Example of Anonymous Classes in PHP

Another example of using anonymous class in PHP is here. The following anonymous class contains function with name sayHello. Actually, this function returns a string “Hello, World!”. Further, in the script we can the method using an instance of the anonymous class. So, it displays the above string.

<?php

// Create an anonymous class that implements the 'HelloWorld' interface
$helloWorld = new class implements HelloWorld {
  public function sayHello() {
    return "Hello World!";
  }
};

// Use the anonymous class
echo $helloWorld->sayHello(); // Outputs: "Hello World!"

?>

As can be seen in the example, the anonymous class implements an interface called HelloWorld. Also, it has a single method sayHello(). As a result, an instance of this class is created and stored in the $helloWorld variable, which can then be used to call the sayHello() method.

Also, note that anonymous classes are only available in PHP 7 or later.


Further Reading

Examples of Array Functions in PHP

Basic Programs in PHP

Registration Form Using PDO in PHP

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *