• PHP Video Tutorials

PHP – The "use" Statement



The "use" keyword in PHP is found to be associated with multiple purposes, such as aliasing, inserting traits and inheriting variables in closures.

Aliasing

Aliasing is accomplished with the use operator. It allows you to refer to an external fully qualified name with an alias or alternate name.

Example

Take a look at the following example −

use My\namespace\myclass as Another;
$obj = new Another;

You can also have groupped use declaration as follows −

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};

Traits

With the help of use keyword, you can insert a trait into a class. A Trait is similar to a class, but only intended to group functionality in a fine-grained and consistent way. It is not possible to instantiate a Trait on its own.

Example

Take a look at the following example −

<?php
   trait mytrait {
      public function hello() {
         echo "Hello World from " . __TRAIT__ .;
      }
   }

   class myclass {
      use mytrait;
   }

   $obj = new myclass();
   $obj->hello();
?>

It will produce the following output

Hello World from mytrait

Closures

Closure is also an anonymous function that can access variables outside its scope with the help of the "use" keyword.

Example

Take a look at the following example −

<?php
   $maxmarks=300;
   $percent=function ($marks) use ($maxmarks) {
      return $marks*100/$maxmarks;
   };
   $m = 250;
   echo "marks=$m percentage=". $percent($m);
?>

It will produce the following output

marks=250 percentage=83.333333333333
Advertisements