Creating PHP interfaces, traits, and classes dynamically at runtime original

by Freek Van der Herten – 2 minute read

PHP is a wonderful dynamic language that's capable of many cool things. I recently stumbled upon something quite fantastic that I want to share with you.

In most projects you'll probably create one class or interface per file.

interface MyInterface
{
}

What is less common is that you can create multiple classes or interfaces per file.

interface MyInterface
{
   // implementation
}

interface AnotherInterface
{
   // implementation
}

What is even less common is that you can conditionally define an interface. As a bonus, you can conditionally extend another interface 🤯.

if ($condition) {
	interface MyInterface
	{
			// implementation
	}
} else {
	interface AnotherInterface extends YetAnotherInterface
	{
		 // another implementation
	}
}

You can also define traits dynamically. So, depending on certain conditions you can add different methods or other implementations.

if ($condition) {
    trait MyTrait
    {
        // add methods
    }
} else {
    trait MyTrait
    {
        // add methods
    }
}

If you got here via /r/php and immediately want to join the army of people commenting "YOUR ARCHITECTURE IS BAD", rest assured that I'm not advocating to use this everywhere. Probably this technique is not needed in most projects. It could be handy in a package that needs to stay compatible with multiple versions of a dependency.

I think it's pretty cool that the dynamic nature of PHP allows for this behaviour and makes it possible for people who need it.

Join 9,500+ smart developers

Get my monthly newsletter with what I learn from running Spatie, building Oh Dear, and maintaining 300+ open source packages. Practical takes on Laravel, PHP, and AI that you can actually use.

No spam. Unsubscribe anytime. You can also follow me on X.

Found something interesting to share? Submit a link to the community section.