如何以及在何处使用php中的关键字"use"

ast*_*idx 3 php namespaces class traits codeception

我一般在类定义之上使用关键字"use".像这样:

<?php
namespace suites\plugins\content\agpaypal;
use \Codeception\Util\Fixtures;
use \Codeception\Verify;
use \Codeception\Specify;

class agpaypalTest extends \Codeception\Test\Unit
{
    protected $tester;
    ...
Run Code Online (Sandbox Code Playgroud)

但是现在我意识到,我必须将特性指定的行放入类定义中.像这样:

 <?php
namespace suites\plugins\content\agpaypal;
use \Codeception\Util\Fixtures;
use \Codeception\Verify;

class agpaypalTest extends \Codeception\Test\Unit
{
    use \Codeception\Specify;

    protected $tester;
    ...
Run Code Online (Sandbox Code Playgroud)

我认为这是因为包\ Codeception\Specify; 是一种特质.但我不明白为什么我设置行use\Codeception\Specify时不能重用这个特性; 在课前定义?

如果有人能指出我的提示或解释,我会很高兴向我解释我应该在哪里使用关键词"使用"最好的.

Ale*_*exM 6

在PHP中,关键字use用于3种情况:

  1. 作为类名别名 - 只需声明一个类的短名称(必须在类定义之外声明)(手册:使用名称空间:别名/导入)
  2. 向类中添加特征(必须在类定义的内部(顶部)声明)(手册:特征)
  3. 在匿名函数定义中传递函数内的变量(手册:匿名函数)