Php 简明教程

PHP – The "use" Statement

PHP 中的“use”关键字被认为与多种用途相关联,例如别名引用、插入特性以及在闭包中继承变量。

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

借助“use”关键字,你可以向类中插入一个特性。特性类似于类,但只打算以细粒度和一致的方式对功能进行分组。不可能自己实例化特性。

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();
?>

它将生成以下 output

It will produce the following output

Hello World from mytrait

Closures

闭包也是一个匿名函数,它可以在“use”关键字的帮助下访问其作用域之外的变量。

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);
?>

它将生成以下 output

It will produce the following output

marks=250 percentage=83.333333333333