Oh Dear is the all-in-one monitoring tool for your entire website. We monitor uptime, SSL certificates, broken links, scheduled tasks and more. You'll get a notifications for us when something's wrong. All that paired with a developer friendly API and kick-ass documentation. O, and you'll also be able to create a public status page under a minute. Start monitoring using our free trial now.

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.

Stay up to date with all things Laravel, PHP, and JavaScript.

You can follow me on these platforms:

On all these platforms, regularly share programming tips, and what I myself have learned in ongoing projects.

Every month I send out a newsletter containing lots of interesting stuff for the modern PHP developer.

Expect quick tips & tricks, interesting tutorials, opinions and packages. Because I work with Laravel every day there is an emphasis on that framework.

Rest assured that I will only use your email address to send you the newsletter and will not use it for any other purposes.

Comments

What are your thoughts on "Creating PHP interfaces, traits, and classes dynamically at runtime"?

Comments powered by Laravel Comments
Want to join the conversation? Log in or create an account to post a comment.