2082 6

BIT301 ยท 2082 ยท 5 marks

What is anonymous class? Write a program to demonstrate the use of anonymous classes.

What is anonymous class? Write a program to demonstrate the use of anonymous classes. [5]

Web Technology IIChapter 6: Object Oriented ProgrammingAnonymous classes

Quick answer

An anonymous class is a class that is defined and instantiated in a single expression and is never given a name. PHP has supported them since version 7, written as new class { ... }. The value of the expression is an object, so the definition and the object creation happen together, which suits a case where an implementation is needed exactly once and a named class kept in its own file would only add noise.

Anonymous classes in PHP

An anonymous class is an ordinary class in every other respect. It may accept constructor arguments, may extend one class, may implement any number of interfaces, and may use traits. Two anonymous classes written at two different places in the code are always distinct classes even when their bodies are identical, and because the class has no name it cannot be referred to, extended or reused elsewhere.

The general form is:

$object = new class ($constructorArguments) extends SomeClass implements SomeInterface {
    // properties and methods
};

A program that uses one

<?php
interface Logger
{
    public function log(string $message): void;
}

class Report
{
    private Logger $logger;

    public function __construct(Logger $logger)
    {
        $this->logger = $logger;
    }

    public function run(string $title): void
    {
        // the title may come from $_GET, so it is escaped before it is written to the
        // page, otherwise a title containing a script tag would run in the browser
        echo "<h3>" . htmlspecialchars($title, ENT_QUOTES, "UTF-8") . "</h3>";
        $this->logger->log("The report " . $title . " was generated.");
    }
}

// an anonymous class supplying a one off implementation of the Logger interface
$report = new Report(new class implements Logger {
    public function log(string $message): void
    {
        echo "<p>LOG: " . htmlspecialchars($message, ENT_QUOTES, "UTF-8") . "</p>";
    }
});

$report->run("Monthly sales");

// an anonymous class that takes a constructor argument of its own
$counter = new class (10) {
    public function __construct(private int $value) {}

    public function next(): int
    {
        return ++$this->value;
    }
};

echo "<p>Next value: " . $counter->next() . "</p>";
?>

The browser receives the heading Monthly sales, then the line LOG: The report Monthly sales was generated., and finally Next value: 11.

What the example shows

FeatureIn the example
Defined and created togethernew class implements Logger { ... }
Implements an interfaceSatisfies the Logger type that Report demands
Takes constructor argumentsnew class (10) { ... } passes 10 to __construct()
Has no nameNothing else in the program can refer to either class

Anonymous classes are used for test doubles, for small strategy or callback objects, and for adapters that exist only to satisfy a type hint. A closure would serve when only one piece of behaviour is needed, but an anonymous class is the right tool when the interface being satisfied has several methods or when the object must carry state between calls.

Short on time? The 1, 5 and 10 mark versions of this answer, flashcards and practice sets come with a program pass.