Anonymous Classes
Part of the Object Oriented Programming section of Coddy's PHP journey — lesson 58 of 91.
Sometimes you need a simple, one-off object without the overhead of defining a full class. Anonymous classes let you create objects on the fly, right where you need them. They're particularly useful when combined with dependency injection.
An anonymous class is defined using new class followed by the class body:
<?php
$logger = new class {
public function log(string $message): void {
echo "Log: $message";
}
};
$logger->log("Hello!");
Output:
Log: Hello!Anonymous classes become powerful when implementing interfaces. This is perfect for testing or when you need a quick implementation without cluttering your codebase with single-use classes:
<?php
interface Notifier {
public function send(string $message): string;
}
function notify(Notifier $notifier, string $msg): string {
return $notifier->send($msg);
}
$result = notify(new class implements Notifier {
public function send(string $message): string {
return "Sent: $message";
}
}, "Test message");
echo $result;
Output:
Sent: Test messageAnonymous classes can also extend other classes, use traits, and accept constructor arguments. They have full access to OOP features - they're just defined inline rather than in a separate file. Use them when a full class definition would be overkill, but you still need object-oriented behavior.
Challenge
EasyLet's build a data formatter system that demonstrates the power of anonymous classes. Instead of creating separate class files for simple, one-off implementations, you'll use anonymous classes to create quick implementations right where you need them.
You'll organize your code across two files:
FormatterInterface.php— Define an interface calledFormatterInterfacewith a single methodformat(string $data): string. This establishes the contract that any formatter must follow.main.php— Include the interface file and create aDataProcessorclass that uses dependency injection to accept any formatter. The class should:- Accept a
FormatterInterfacein its constructor - Have a method
process(string $data)that delegates to the injected formatter and returns its result
You'll receive two inputs: a format type (
"upper"or"reverse") and a string to format.Based on the format type, create an anonymous class that implements
FormatterInterface:- For
"upper": theformat()method should return the data converted to uppercase - For
"reverse": theformat()method should return the data reversed
Inject your anonymous class into a
DataProcessor, callprocess()with the input string, and print the result.- Accept a
This approach is perfect when you need a quick implementation without cluttering your codebase with single-use class files. The anonymous class is created inline, implements the required interface, and can be passed anywhere that interface is expected.
Cheat sheet
Anonymous classes allow you to create objects on the fly without defining a full class. They're defined using new class followed by the class body:
<?php
$logger = new class {
public function log(string $message): void {
echo "Log: $message";
}
};
$logger->log("Hello!");
Anonymous classes can implement interfaces, making them useful for dependency injection and testing:
<?php
interface Notifier {
public function send(string $message): string;
}
function notify(Notifier $notifier, string $msg): string {
return $notifier->send($msg);
}
$result = notify(new class implements Notifier {
public function send(string $message): string {
return "Sent: $message";
}
}, "Test message");
Anonymous classes support all OOP features: they can extend other classes, use traits, and accept constructor arguments. Use them when a full class definition would be overkill but you still need object-oriented behavior.
Try it yourself
<?php
require_once 'FormatterInterface.php';
// TODO: Create a DataProcessor class that:
// - Accepts a FormatterInterface in its constructor
// - Has a process(string $data) method that delegates to the formatter
// Read input
$formatType = trim(fgets(STDIN));
$inputString = trim(fgets(STDIN));
// TODO: Based on $formatType ("upper" or "reverse"), create an anonymous class
// that implements FormatterInterface
// - For "upper": format() should return uppercase version of data
// - For "reverse": format() should return reversed version of data
// TODO: Create a DataProcessor with your anonymous class formatter
// Call process() with the input string and print the result
?>This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesIntroduction to OOPClasses vs ObjectsThe $this KeywordMethodsPropertiesConstructor (__construct)Destructor (__destruct)Recap - Simple Calculator4Inheritance
Basic InheritanceThe parent:: KeywordMethod OverridingThe final KeywordAbstract ClassesRecap - Employee Hierarchy7Encapsulation
Public, Protected, PrivateAccess Modifiers in DepthGetters and SettersInformation HidingConstructor Promotion (8.0)Recap - Student Records System10Advanced OOP Concepts
Composition vs InheritanceDependency InjectionAnonymous ClassesEnums (PHP 8.1)Fibers (PHP 8.1)Object Cloning Deep DiveGenerators & Iterators2Namespaces & Autoloading
Introduction to NamespacesThe use KeywordPSR-4 Autoloading StandardComposer AutoloaderRecap - Organized Project5Interfaces & Contracts
Introduction to InterfacesImplementing InterfacesMultiple Interface ImplementInterface vs Abstract ClassType Hinting with InterfacesRecap - Shape Calculator8Magic Methods
Magic Methods Introduction__toString & __debugInfo__get, __set, __isset, __unset__call & __callStatic__clone & Object Cloning__serialize & __unserializeRecap - Custom Collection11Type System & Error Handling
Type DeclarationsNullable TypesUnion & Intersection TypesException ClassesCustom Exception HierarchyTry, Catch, FinallyRecap - Form Validator14Project: Library Management
Project OverviewBook and User Classes3Class Properties
Instance vs Static PropertiesConstants in ClassesStatic Methods & PropertiesPrivate & Protected PropertiesReadonly Properties (PHP 8.1)Recap - Bank Account Manager6Polymorphism
Method Overriding RevisitedPolymorphism via InterfacesType Hinting & Union TypesLate Static BindingRecap - Payment Processor9Traits
Introduction to TraitsUsing Multiple TraitsTrait Conflict ResolutionAbstract Methods in TraitsTraits vs Inheritance12Design Patterns Part 1
Intro to Design PatternsSingleton PatternFactory PatternObserver PatternStrategy Pattern