← CodeClarityLab Home
Browse by Category
+ added · updated 7d
← Back to glossary

Anonymous Classes (PHP 7.0)

php PHP 7.0+ Intermediate
debt(d6/e3/b2/t4)
d6 Detectability Operational debt — how invisible misuse is to your safety net

Closest to 'specialist tool catches' (d5), +1. PHPStan can detect some patterns (e.g., unused named stub classes that could be anonymous), but the decision of when to use anonymous classes vs named classes vs closures is largely a design judgment call. The detection_hints note 'automated: no', meaning no tool reliably flags misuse. Careful code review is needed to spot cases where anonymous classes should or shouldn't be used, pushing this above d5 toward d7 but not fully there since PHPStan can catch some type-related issues with anonymous class usage.

e3 Effort Remediation debt — work required to fix once spotted

Closest to 'simple parameterised fix' (e3). The quick_fix is straightforward: replace a named single-use class with an inline anonymous class definition, or vice versa. This typically touches one or two files (the test file and possibly removing the named class file). It's a localized refactor within one component, not cross-cutting.

b2 Burden Structural debt — long-term weight of choosing wrong

Closest to 'minimal commitment' (b1), +1. Anonymous classes are localized constructs — each instance is self-contained at a single call site. They don't impose structural weight across the codebase. However, they do carry a minor maintenance tax: debugging is harder (get_class returns internal identifiers), and team members need to understand the pattern. The reach is minimal since they apply to individual usage sites, but they appear across all PHP contexts (web, cli, queue-worker).

t4 Trap Cognitive debt — how counter-intuitive correct behaviour is

Closest to 'minor surprise' (t3), +1. The misconception states developers think anonymous classes are 'just shorthand for small named classes,' missing their value in tests and inline interface implementations. Common mistakes include not knowing they can extend classes and implement interfaces, and using them where closures would suffice. These are notable but not severe traps — a competent developer will likely guess some behaviors wrong (especially around capabilities like implementing interfaces) but will learn quickly. The debugging surprise with class_name returning internal identifiers adds another gotcha.

About DEBT scoring →

Also Known As

PHP anonymous classes inline class new class{}

TL;DR

Classes without a name, defined inline with new class — useful for one-off implementations and test doubles.

Explanation

Anonymous classes (PHP 7.0+) are declared with new class { ... } and can extend, implement interfaces, and accept constructor arguments. They are ideal for lightweight one-off implementations (mocking an interface inline in a test, creating a small callback object) without the overhead of a named class file. The class has an internal generated name but cannot be referenced by name later. Anonymous classes are slightly slower to instantiate than named classes due to class registration overhead — avoid them in tight loops.

Common Misconception

Anonymous classes are just a shorthand for small named classes. They are also invaluable in tests for creating one-off stubs without defining a named class, and in frameworks for inline interface implementations that are used in exactly one place.

Why It Matters

Anonymous classes allow single-use implementations of interfaces or abstract classes without the overhead of named class declarations — ideal for test doubles, adapters, and one-time callbacks.

Common Mistakes

  • Creating named classes for single-use implementations — anonymous classes are cleaner for short-lived objects.
  • Assuming anonymous classes cannot implement interfaces or extend — they can do both.
  • Using anonymous classes where a simple closure would suffice — closures are lighter for pure function behaviour.
  • Debugging anonymous classes is harder — class_name returns an internal identifier; document them clearly.

Avoid When

  • The class is instantiated in more than one place — give it a name so it can be reused and referenced in type hints.
  • The class carries significant logic — anonymous classes are hard to find, document, and test in isolation.
  • You need to type-hint the concrete class anywhere; anonymous classes produce an unspeakable internal name.

When To Use

  • Creating lightweight test doubles inline — no need for a dedicated class file for a one-method stub.
  • Implementing a simple interface for a single call site where naming the class adds no clarity.
  • Factory methods that return a private implementation without exposing the class name to callers.

Code Examples

💡 Note
The good example inlines a no-op logger for a test without creating a separate DiscardingLogger file — appropriate for a one-off stub that will never be reused.
✗ Vulnerable
// Creating a full file just for a trivial one-use implementation
✓ Fixed
$logger = new class implements LoggerInterface {
  public function log(string $msg): void { /* no-op */ }
};

Added 15 Mar 2026
Edited 31 Mar 2026
Views 41
Rate this term
No ratings yet
🤖 AI Guestbook educational data only
| |
Last 30 days
0 pings T 0 pings F 0 pings S 0 pings S 0 pings M 0 pings T 1 ping W 0 pings T 2 pings F 0 pings S 1 ping S 0 pings M 1 ping T 0 pings W 0 pings T 1 ping F 0 pings S 1 ping S 0 pings M 0 pings T 0 pings W 2 pings T 1 ping F 0 pings S 0 pings S 0 pings M 0 pings T 0 pings W 0 pings T 0 pings F
No pings yet today
No pings yesterday
Ahrefs 15 Perplexity 7 Amazonbot 6 Google 4 SEMrush 3 Bing 1
crawler 33 crawler_json 3
DEV INTEL Tools & Severity
🟢 Low ⚙ Fix effort: Low
⚡ Quick Fix
Use anonymous classes in tests to create lightweight one-off implementations of interfaces without creating named test double classes for every case
📦 Applies To
PHP 7.0+ web cli queue-worker
🔗 Prerequisites
🔍 Detection Hints
Creating named single-use stub classes only used in tests; simple interface implementation needing no reuse
Auto-detectable: ✗ No phpstan
⚠ Related Problems
🤖 AI Agent
Confidence: Low False Positives: High ✗ Manual fix Fix: Low Context: Function

✓ schema.org compliant