Menu
Coddy logo textTech

Anonymous Classes

Part of the Object Oriented Programming section of Coddy's PHP journey — lesson 58 of 91.

Sometimes you need a simple, one-off object without the overhead of defining a full class. Anonymous classes let you create objects on the fly, right where you need them. They're particularly useful when combined with dependency injection.

An anonymous class is defined using new class followed by the class body:

<?php
$logger = new class {
    public function log(string $message): void {
        echo "Log: $message";
    }
};

$logger->log("Hello!");

Output:

Log: Hello!

Anonymous classes become powerful when implementing interfaces. This is perfect for testing or when you need a quick implementation without cluttering your codebase with single-use classes:

<?php
interface Notifier {
    public function send(string $message): string;
}

function notify(Notifier $notifier, string $msg): string {
    return $notifier->send($msg);
}

$result = notify(new class implements Notifier {
    public function send(string $message): string {
        return "Sent: $message";
    }
}, "Test message");

echo $result;

Output:

Sent: Test message

Anonymous classes can also extend other classes, use traits, and accept constructor arguments. They have full access to OOP features - they're just defined inline rather than in a separate file. Use them when a full class definition would be overkill, but you still need object-oriented behavior.

challenge icon

Challenge

Easy

Let's build a data formatter system that demonstrates the power of anonymous classes. Instead of creating separate class files for simple, one-off implementations, you'll use anonymous classes to create quick implementations right where you need them.

You'll organize your code across two files:

  • FormatterInterface.php — Define an interface called FormatterInterface with a single method format(string $data): string. This establishes the contract that any formatter must follow.
  • main.php — Include the interface file and create a DataProcessor class that uses dependency injection to accept any formatter. The class should:
    • Accept a FormatterInterface in its constructor
    • Have a method process(string $data) that delegates to the injected formatter and returns its result

    You'll receive two inputs: a format type ("upper" or "reverse") and a string to format.

    Based on the format type, create an anonymous class that implements FormatterInterface:

    • For "upper": the format() method should return the data converted to uppercase
    • For "reverse": the format() method should return the data reversed

    Inject your anonymous class into a DataProcessor, call process() with the input string, and print the result.

This approach is perfect when you need a quick implementation without cluttering your codebase with single-use class files. The anonymous class is created inline, implements the required interface, and can be passed anywhere that interface is expected.

Cheat sheet

Anonymous classes allow you to create objects on the fly without defining a full class. They're defined using new class followed by the class body:

<?php
$logger = new class {
    public function log(string $message): void {
        echo "Log: $message";
    }
};

$logger->log("Hello!");

Anonymous classes can implement interfaces, making them useful for dependency injection and testing:

<?php
interface Notifier {
    public function send(string $message): string;
}

function notify(Notifier $notifier, string $msg): string {
    return $notifier->send($msg);
}

$result = notify(new class implements Notifier {
    public function send(string $message): string {
        return "Sent: $message";
    }
}, "Test message");

Anonymous classes support all OOP features: they can extend other classes, use traits, and accept constructor arguments. Use them when a full class definition would be overkill but you still need object-oriented behavior.

Try it yourself

<?php
require_once 'FormatterInterface.php';

// TODO: Create a DataProcessor class that:
// - Accepts a FormatterInterface in its constructor
// - Has a process(string $data) method that delegates to the formatter

// Read input
$formatType = trim(fgets(STDIN));
$inputString = trim(fgets(STDIN));

// TODO: Based on $formatType ("upper" or "reverse"), create an anonymous class
// that implements FormatterInterface
// - For "upper": format() should return uppercase version of data
// - For "reverse": format() should return reversed version of data

// TODO: Create a DataProcessor with your anonymous class formatter
// Call process() with the input string and print the result

?>
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming