dqqy64515 2017-04-04 02:44
浏览 37
已采纳

PHP - 在类之外使用关键字的区别,并在类中使用关键字

Good day guys!

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.

Example:

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
    }
  • 写回答

1条回答 默认 最新

  • drpjdfj618393 2017-04-04 04:43
    关注

    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;
    

    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'
    

    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
        }
    }
    

    From the example above, you have direct access to incrementLoginAttempts(), which is defined the ThrottlesLogins.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测