PHP-类外的use关键字与类内的use关键字的区别 [英] PHP - difference of use keyword outside of class and use keyword inside of a class
问题描述
大家好!
只想问一下class
内class
和 use 的区别?我也用谷歌搜索,但是我的问题与答案不符.
Just want to ask the difference of use outise the class
and use inside the class
? I have also googled it, but my question doesnt match an answer.
示例:
namespace App\Http\Controllers\Auth;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
use Auth;
use Illuminate\Http\Request;
class AuthController extends Controller
{
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
protected $redirectTo = '/';
/**
* Create a new authentication controller instance.
*
* @return void
*/
public function __construct()
{
// Some Code
}
推荐答案
定义类时,它只能访问其命名空间中的其他类.例如,您的控制器在以下名称空间中定义.
When you define a class, it can only have access to other classes within its namespaces. Your controller for instance is defined within the following namespace.
namespace App\Http\Controllers\Auth;
因此,要使用其他类,您需要从它们自己的名称空间中导入它们,以便可以访问它们.例如:
So to use other classes, you need to import them from their own namespaces so you can access them. e.g.:
use Illuminate\Foundation\Auth\ThrottlesLogins;
如果您具有JavaScript ES6经验,则与import
有点相似.导入软件包时,默认名称空间为/node_modules
.要导入自己的文件,您需要通过给文件位置类似
If you have javascript ES6 experience, it's a little bit similar to import
. When you import a package, the default namespace is /node_modules
. To import your own files, you need to sort of namespace them by giving the file location like
import '../containers/index.js'
回到Laravel.现在,您已经导入了ThrottlesLogins
(实际上是一个特征),现在将其放入类中,以显示所有内部方法.
Back to Laravel. Now that you have imported the ThrottlesLogins
, which is actually a trait, now inside the class you use
it to expose all of the methods inside.
use Illuminate\Foundation\Auth\ThrottlesLogins; //import
public class AuthController
{
use ThrottlesLogins; //exposes all the methods inside
...
public function login()
{
...
//login failed
$this->incrementLoginAttempts(); //defined in ThrottlesLogins Trait
}
}
在上面的示例中,您可以直接访问定义为ThrottlesLogins
的incrementLoginAttempts()
.
From the example above, you have direct access to incrementLoginAttempts()
, which is defined the ThrottlesLogins
.
这篇关于PHP-类外的use关键字与类内的use关键字的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!