【问题标题】:Php make variable in construct function available to other functions within controllerphp 使构造函数中的变量可用于控制器中的其他函数
【发布时间】:2017-11-20 11:58:57
【问题描述】:

我有一个带有 __construct 的控制器,比如这个:

class ApiController extends Controller
{
    protected $auth;

    public function __construct()
    {
        $auth = UserRepository::check();
        return $auth;
    }

我想要做的是当我创建一个新函数时,即

public function test() {
  dd($auth);
}

但是它说变量没有定义。如何使其可用于其他功能而不仅仅是构造?

【问题讨论】:

标签: php laravel laravel-5


【解决方案1】:

使用$this关键字设置/获取类变量

这样设置

public function __construct()
{
    $this->auth = UserRepository::check();
}

然后变成这样

public function test() {
  return dd($this->auth);
}

【讨论】:

  • 感谢您的理解
【解决方案2】:

$auth 是构造函数的局部变量。如果希望类中的方法使用该变量,则需要将值分配给 $this->auth 而不是 $auth$this 指的是当前对象。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-01
    • 2017-04-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-17
    • 1970-01-01
    相关资源
    最近更新 更多