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 −
useMy\namespace\myclassas Another;$obj=newAnother;
You can also have groupped use declaration as follows −
use some\namespace\{ClassA, ClassB, ClassC asC};usefunction some\namespace\{fn_a, fn_b, fn_c};useconst 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
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
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 −
Open Compiler
<?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
Leave a Reply