PHP Anonymous Classes – Create Lightweight, One-Off Objects on the Fly

Learn how to use anonymous classes in PHP to define and instantiate objects without giving them a formal class name.


Introduction – What Are Anonymous Classes in PHP?

Anonymous classes in PHP allow you to create a class and an object at the same time, without giving the class a name. Introduced in PHP 7, they’re ideal for short-lived, one-off objects used in event handlers, testing, closures, or temporary logic.

In this guide, you’ll learn:

  • How to create and use anonymous classes
  • When to use anonymous classes instead of named ones
  • How to implement interfaces or extend classes anonymously
  • Best practices for efficient, readable usage

1. Creating a Basic Anonymous Class

$logger = new class {
    public function log($msg) {
        echo "[LOG]: $msg";
    }
};

$logger->log("Hello world!"); // [LOG]: Hello world!

Use the new class keyword to define and instantiate simultaneously.
Perfect for small, self-contained behaviors.


2. Anonymous Class with Constructor

$alert = new class("System failure") {
    private $message;

    public function __construct($msg) {
        $this->message = $msg;
    }

    public function show() {
        echo $this->message;
    }
};

$alert->show(); // System failure

You can pass constructor arguments just like with regular classes.
Useful for dependency injection or dynamic configuration.


3. Implementing Interfaces with Anonymous Classes

interface Greeter {
    public function greet();
}

$greeter = new class implements Greeter {
    public function greet() {
        echo "Hello from anonymous class!";
    }
};

$greeter->greet(); // Hello from anonymous class!

Anonymous classes can implement interfaces or even extend base classes.
This is powerful for mocking, strategy patterns, or callbacks.


4. Extending a Class Anonymously

class BaseLogger {
    public function info($msg) {
        echo "[INFO]: $msg";
    }
}

$customLogger = new class extends BaseLogger {
    public function error($msg) {
        echo "[ERROR]: $msg";
    }
};

$customLogger->info("Start");
$customLogger->error("Something went wrong");

You can extend existing classes to enhance or override functionality.
Makes temporary modifications easy without creating a new class file.


Best Practices

  • Use for quick, local objects that don’t need reuse
  • Keep logic simple and self-contained
  • Implement interfaces when using in dependency injection
  • Don’t use for large logic blocks — prefer named classes
  • Useful in testing, mocks, and closures

Summary – Recap & Next Steps

PHP anonymous classes provide a lightweight alternative to regular class definitions when you only need the behavior once. They offer the full power of classes — constructors, inheritance, interfaces — all inline.

Key Takeaways:

  • Anonymous classes are created using new class {}
  • Great for short-lived, one-off objects
  • Support inheritance, interfaces, constructors, and visibility
  • Cleaner than defining throwaway named classes

Real-World Use Cases:
Temporary formatters, test mocks, closure callbacks, inline service implementations, strategy pattern injections


Frequently Asked Questions (FAQs)

When should I use an anonymous class?
When you need a one-time-use class and want to avoid cluttering your codebase.

Can anonymous classes have properties and methods?
Yes, just like regular classes — including private, public, protected.

Can anonymous classes be reused?
No. Once instantiated, they’re not referenceable by name.

Can I type-hint an anonymous class?
Only if it implements an interface or extends a known base class.

Are anonymous classes slower than named classes?
Slightly — but the performance impact is negligible in most applications.


Share Now :
Share

🕵️ PHP Anonymous Classes

Or Copy Link

CONTENTS
Scroll to Top