PHP Anonymous Class

Summary: in this tutorial, you’ll learn how about the PHP anonymous class and how to define anonymous classes.

Introduction to the PHP anonymous classes

So far, you have learned how to define a new class with a name. For example:

<?php

class MyClass 
{
    // ...
}Code language: PHP (php)

The MyClass is called a named class.

An anonymous class is a class without a declared name. The following creates an object of anonymous class:

<?php

$myObject = new class {
    // ...
};Code language: PHP (php)

In this syntax, you place the class keyword after the new keyword. The $myObject is the instance of the anonymous class.

Inside the parentheses, you can define constructor, destructor, properties, and methods for the anonymous class like a regular class. For example:

<?php

$logger = new class {
    public function log(string $message): void
    {
        echo $message . '<br>';
    }
};

$logger->log('Hello');Code language: PHP (php)

How it works.

First, create the $logger object of the anonymous class that has one method log() that displays a message with a
tag.

Second, call the log() method via the $logger object.

Internally, PHP generates a name for the anonymous class. To get the generated name, you can use the get_class() function. For example:

echo get_class($logger);Code language: PHP (php)

Output:

index.php0000025F568665BECode language: PHP (php)

PHP manages this class name internally. Therefore, you should not rely on it.

Implementing an interface

An anonymous can implement one or multiple interfaces. For example:

<?php

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

$logger = new class implements Logger {
    public function log(string $message): void
    {
        echo $message . '<br>';
    }
};

$logger->log('Hello');Code language: PHP (php)

In this example, we define the Logger interface that has the log() method. And then, we define an anonymous class that implements the Logger interface.

The $logger is the instance of the Logger interface:

echo $logger instanceof Logger; // trueCode language: PHP (php)

Because an anonymous doesn’t have a declared name, you cannot use the type hint for its instance.

However, when an anonymous class implements an interface, you can use the type hint via the interface. For example:

<?php

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

$logger = new class implements Logger {
    public function log(string $message): void
    {
        echo $message . '<br>';
    }
};

// type hint
function save(Logger $logger)
{
    $logger->log('The file was updated successfully.');
}

save($logger);Code language: PHP (php)

Inheriting a class

Like a regular class, a class can inherit from one named class. For example:

<?php

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

abstract class SimpleLogger implements Logger
{
    protected $newLine;

    public function __construct(bool $newLine)
    {
        $this->newLine = $newLine;
    }

    abstract public function log(string $message): void;
}

$logger = new class(true) extends SimpleLogger {
    public function __construct(bool $newLine)
    {
        parent::__construct($newLine);
    }

    public function log(string $message): void
    {
        echo $this->newLine ? $message . PHP_EOL : $message;
    }
};

$logger->log('Hello');
$logger->log('Bye');Code language: PHP (php)

How it works.

First, define an interface called Logger that has one method log().

Second, define an abstract class called SimpleLogger that implements the Logger interface.

Third, define an anonymous class that extends the SimpleLogger class. We call the constructor of the SimpleLogger class in the constructor of the anonymous class.

To pass an argument to the constructor, we place it in parentheses that follow the class keyword.

Finally, call the log() method of the $logger object.

When to use anonymous classes

Anonymous classes are helpful in some cases:

First, anonymous classes make it easy to mock tests. Note that you’ll learn about unit testing with PHPUnit later.

Second, anonymous classes keep their usage outside the scope where they are defined. For example, instead of doing this:

<?php

class ConsoleLogger 
{
    public function log($message) 
    {
        echo $message . PHP_EOL;
    }
}

$obj->setLogger(new ConsoleLogger());Code language: PHP (php)

Now, you can make use the an anonymous class like this:

$obj->setLogger(new class {
    public function log($msg) {
       echo $message . PHP_EOL;
    }
});Code language: PHP (php)

Third, make a small optimization by avoid hitting the autoloader for trivial classes.

Summary

  • An anonymous class is a class without a declared name.
Did you find this tutorial useful?