如何从扩展控制器获取变量?

时间:2015-05-06 13:20:12

标签: php controller laravel-5

我有这个基本控制器:

abstract class ApiController extends BaseController {

use DispatchesCommands, ValidatesRequests;
public function __construct()
{
    try {
        $user = JWTAuth::parseToken()->toUser();
    } catch (Exception $e) {
        return Response::json(['error' => $e->getMessage()], HttpResponse::HTTP_UNAUTHORIZED);
    }
}
}

如何在子控制器中获取$ user变量?如果可能,请提供示例儿童控制器。

1 个答案:

答案 0 :(得分:1)

首先:

abstract class ApiController extends BaseController {

  use DispatchesCommands, ValidatesRequests;

  protected $user; // or public
  public function __construct()
  {
    try {
        $this->user = JWTAuth::parseToken()->toUser();
    } catch (Exception $e) {
        return Response::json(['error' => $e->getMessage()], HttpResponse::HTTP_UNAUTHORIZED);
    }
  }
}

然后:

class Ctrl extends ApiController
{
  public function whatever()
  {
    echo $this->user;
  }
}

最后但并非最不重要:http://www.phpfreaks.com/tutorial/oo-php-part-1-oop-in-full-effect

快乐的编码!