Make Use of Grouped Use Statements in PHP7+

2020-04-17

Since php7 we can use grouped use statements to make multiple classes of a namespace available through a single use statement. Let's take a look at this approach and how we can benefit from it.

When using libraries like the one from stripe (opens new window), you are very likely to include multiple classes from the same namespace. Prior to php7 you would have done this like so.

<?php

namespace Acme\Foo;

use Stripe\Stripe;
use Stripe\Charge;
use Stripe\Customer;

class Bar {
    ...
}

This can lead to large header sections in your classes. Luckily, a lot of editors just hide this portion from you, but still, it's not so pretty.

Php7 introduced a new way to handle this, using grouped use statements (opens new window).

<?php

namespace Acme\Foo;

use Stripe\{Stripe, Charge, Customer};

class Bar {
    ...
}

This approach feels a lot like the import ... from ... syntax of javascript but I guess this is way better then having large blocks of use statements at the top of your classes.