Programster's Blog

Tutorials focusing on Linux, programming, and open-source

PHP 7.0 - Anonymous Classes

A new feature of php 7.0 is anonymous classes. Anonymous classes are useful when simple, one-off objects need to be created, such as a value object. Below is an example of using an anonymous class for ensuring a user provided string is valid, and converts it for later use.

// set a value for this example, but imagine the user 
// was posting this in a form.
$_POST['var1'] = 'another_type'; 

$valueObj = new class($_POST['var1']) {
    private $m_value;

    public function __construct(string $input)
    {
        switch ($input)
        {
            case 'type1' : $this->m_value = 1; break;
            case 'type2' : $this->m_value = 2; break;
            case 'another_type' : $this->m_value = 3; break;
            default : throw new Exception("Invalid input: $input");
        }
    }

    public function getValue() : int { return $this->m_value; }
};

print $valueObj->getValue(); // 3

Remember that you have created an object, rather than a class definition, so you couldn't do this:

$myOtherObj = new $valueObj('type2);

Another possible use for anonymous classes is to create a one off object that implements an interface for dependency injection rather than having to create a whole new class file somewhere. E.g.

interface Logger 
{
    public function log(string $input);
}

class MyClassThatRequiresALogger
{
    private $m_logger;

    public function __construct(Logger $logger)
    {
        $this->m_logger = $logger;
    }

    public function run()
    {
        // do something here...
        $this->m_logger->log("I did something!");
    }
}

$logger = new class()  implements Logger {
    public function log(string $input) { print($input); }
};

$myClass = new MyClassThatRequiresALogger($logger);
$myClass->run(); // I did something!
Last updated: 16th September 2021
First published: 16th August 2018

This blog is created by Stuart Page

I'm a freelance web developer and technology consultant based in Surrey, UK, with over 10 years experience in web development, DevOps, Linux Administration, and IT solutions.

Need support with your infrastructure or web services?

Get in touch