Articles/PHP/Using Anonymous Classes in PHP

Using Anonymous Classes in PHP

As of PHP 7, you can now create quick throwaway objects for use within your projects. This can be especially useful for your automated tests, for instance, with allowing you to create quick implementations of your interfaces.

November 12, 2016·1 min read

As of PHP 7, you can now create quick throwaway objects for use within your projects. This can be especially useful for your automated tests, for instance, by allowing you to create quick implementations of your interfaces.

Let's review a Notifier interface that we may have. We can easily create an anonymous implementation by using the new keyword followed by the keyword class. Let's look at a basic example below.

Example

PHP
<?php

interface Notifier
{
    public function send($to);
}

$anonymousClass = new class implements Notifier
{
    public function send($to)
    {
        return 'Notification sent to ' . $to;
    }
};