我应该如何以及在何处使用关键字"use"?在PHP中 [英] How and where should I use the keyword "use" in php

查看:90
本文介绍了我应该如何以及在何处使用关键字"use"?在PHP中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通常在类定义上方使用关键字"use".像这样:

I used use the keyword "use" generally above the class definition. Like this:

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

class agpaypalTest extends \Codeception\Test\Unit
{
    protected $tester;
    ...

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

But now I realised, that I have to put the line for the trait Specify into the class definition. Like this:

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

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

    protected $tester;
    ...

我认为这是因为软件包\ Codeception \ Specify;是一个特质.但是我不明白为什么我在设定界限时不能重复使用此特征 使用\ Codeception \ Specify; 在课程定义之前?

I think it is because the package \Codeception\Specify; is a trait. But I do not understand why I couldn't reuse this trait when I set the line use \Codeception\Specify; before the class definition?

如果有人可以向我提示或解释我可以在哪里最好使用关键字使用",我会很高兴.

I would be happy if someone could point me to a hint or an explanaiton that explains to me where I should use the keyword "use" the best.

推荐答案

在PHP中,在三种情况下使用关键字use:

In PHP, the keyword use is used in 3 cases:

  1. 作为类名别名-只需声明一个类的简称(必须在类定义的外部中声明) (手册:使用名称空间:别名/导入)
  2. 向类添加特征(必须在类定义的内部中(顶部)声明) (手册:特征)
  3. 在匿名函数定义中,以在函数内部传递变量 (手册:匿名函数)
  1. As class name alias - simply declares short name for a class (must be declared outside of the class definition) (manual: Using namespaces: Aliasing/Importing )
  2. To add a trait to a class (must be declared inside (at the top) of the class definition) (manual: Traits)
  3. In anonymous function definition to pass variables inside the function (manual: Anonymous functions)

这篇关于我应该如何以及在何处使用关键字"use"?在PHP中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆