Types of Group Use declarations in PHP 7

PHPServer Side ProgrammingProgramming

PHP 7 uses three different types of Group Use declarations −

  • Non-mixed-use declarations
  • Mixed-use declarations
  • Compound use declarations

Non-mixed-use declarations:

Non-mixed-use declaration means we do not use the classes, functions, and constructs in a single statement. Or, we can say that when we declare classes, functions, and constants separately using a use statement. It is called Non-mixed group use declarations.

Example

use Publishers\Packt\{ Book, Ebook, Video, Presentation };
use function Publishers\Packt\{ getBook, saveBook };
use const Publishers\Packt\{ COUNT, KEY };

Mixed group use declarations

When we combine the PHP class, function and constants in a single-use statement, it is called a mixed group use declaration.

Example

use Publishers\Packt\
{
   Book,
   Ebook,
   Video,
   Presentation,
   function getBook,
   function saveBook,
   const COUNT,
   const KEY
};

Compound use declarations

We can say that compound use declaration is more classic and clear, and it also doesn't require extra typing if the namespace names are large.

Suppose we have a book class in the publishers\packet\paper namespace, and also an ebook class in the publishers\packet\electronic namespace, and audio, presentation classes are in the publishers\packet\media namespace.We can write all these as follows −

Example

use Publishers\Packet\Paper\Book; use Publishers\Packet\Electronic\Ebook; use Publishers\Packet\Media\{Audio,Presentation};

Now, let’s rewrite the same code using the Compound Use declaration −

use Publishers\Packet\{
   Paper\Book,
   Electronic\Ebook,
   Media\Audio,
   Media\Presentation
};
raja
Published on 13-Mar-2021 06:14:36
Advertisements