Group Use declarations in PHP 7


In PHP 7,Group Use declaration is more readable and can be used to import classes, constants, and functions easily from the same namespace.

Group Use declaration is used to import multiple structures easily from a namespace and cuts a good level of volubility in most cases. It is also useful to identify the multiple imported entities which belong to the same module.

Example 1

The following example shows the code before PHP 7 −

<?php
   use com\India\ClassX;
   use com\India\ClassY;
   use com\India\ClassZ as Z;

   use function com\India\fn_x;
   use function com\Indiat\fn_y;
   use function com\India\fn_z;

   use const com\India\ConstX;
   use const com\India\ConstY;
   use const com\India\ConstZ;
?>

Example 2

The following example shows the code for PHP7 or PHP 7+

use com\India\{ClassX, ClassY, ClassZ as Z};
use function com\India\{fn_x,fn_y, fn_z};
use const com\India\{ConstX, ConstY, ConstZ};

Explanation

In Example 1, we used PHP statements for specific classes, functions, and constants in a namespace and also used many duplicate lines for each class, function, and constant with lots of use statements at the top of the file which is not good.

Example 2 shows the equivalent code in PHP 7 where we are using multiple class, function, and constants within one line

Note: To overcome the multiple-use statements and classes PHP 7 added a new feature called group use declaration.

Updated on: 13-Mar-2021

614 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements