Run
Run

Reputation: 57176

PHP - use Namespace\{Foo, Bar}?

When did PHP have this below?

use Namespace\{Foo, Bar}

I came across this pattern from the php pleague:

namespace Acme;

class Foo
{
    /**
     * @type Acme\Bar
     */
    public $bar;

    /**
     * Construct.
     *
     * @param \Acme\Bar $bar
     */
    public function __construct(Bar $bar)
    {
        $this->bar = $bar;
    }
}

class Bar
{
    // ...
}

And then:

<?php

use Acme\{Foo, Bar};

Is it valid? If it is, where can study this further?

Upvotes: 3

Views: 279

Answers (2)

Matthew Daly
Matthew Daly

Reputation: 9476

According to the docs, it's valid in PHP7 and upwards:

From PHP 7.0 onwards, classes, functions and constants being imported from the same namespace can be grouped together in a single use statement.

They provide the following example:

<?php

// Pre PHP 7 code
use some\namespace\ClassA;
use some\namespace\ClassB;
use some\namespace\ClassC as C;

use function some\namespace\fn_a;
use function some\namespace\fn_b;
use function some\namespace\fn_c;

use const some\namespace\ConstA;
use const some\namespace\ConstB;
use const some\namespace\ConstC;

// PHP 7+ code
use some\namespace\{ClassA, ClassB, ClassC as C};
use function some\namespace\{fn_a, fn_b, fn_c};
use const some\namespace\{ConstA, ConstB, ConstC};

Upvotes: 2

BenM
BenM

Reputation: 53198

Yes, it's valid. It was introduced in PHP 7.0. From the docs:

From PHP 7.0 onwards, classes, functions and constants being imported from the same namespace can be grouped together in a single use statement.

<?php

// Pre PHP 7 code
use some\namespace\ClassA;
use some\namespace\ClassB;
use some\namespace\ClassC as C;

...

// PHP 7+ code
use some\namespace\{ClassA, ClassB, ClassC as C};
use function some\namespace\{fn_a, fn_b, fn_c};
use const some\namespace\{ConstA, ConstB, ConstC};

Upvotes: 5

Related Questions