Frank Perez

Frank Perez

Keep in touch

An experienced Web Developer with years of experience in design, programming and server administration.

Blog

Overview

© 2018 by Frank Perez.

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.

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

Example

<?php

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

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