Laravel 不能在匿名函数中使用 $this

Laravel Cannot use $this Inside Anonymous Function

我正在使用一个构造来只获取一次请求变量,因为我需要在多个方法中使用它们,所以我不想重复代码。

public function __construct(Request $request)
{
    $this->labelId   = $request->label;
    $this->statusId  = $request->status;
    $this->monthId   = $request->month;
}

这适用于我的 "standard" 视图,但不适用于 "label view":

public function standard()
{
    $appointments = Appointment::latest('start')->status($this->statusId)->label($this->labelId)->month($this->monthId)->get();

    return view('appointments.index', compact('appointments'));
}

public function label(Request $request)
{
    $appointments = Label::with(['appointments' => function ($query) use ($this->labelId, $this->statusId, $this->monthId) {
        $query->label($this->labelId)->status($this->statusId)->month($this->monthId)->get();
    }])->get();

    return view('appointments.label', compact('appointments'));
}

我收到错误:

Cannot use $this as lexical variable

问题在这里:

function ($query) use ($this->labelId, $this->statusId, $this->monthId)

我的问题是,我能否以某种方式在使用构造的标签方法中使用变量,或者是否有更好的方法来完成此操作?

替换:

$appointments = Label::with(['appointments' => function ($query) use ($this->labelId, $this->statusId, $this->monthId) {
    $query->label($this->labelId)->status($this->statusId)->month($this->monthId)->get();
}])->get();

与:

$appointments = Label::with(['appointments' => function ($query) {
    $query->label($this->labelId)->status($this->statusId)->month($this->monthId)->get();
}])->get();

can't pass properties of the current object via use(),你不能 use($this),但是,$this 在 PHP 5.4+ 中始终可用。

要使其正常运行,您需要 PHP 5.4+。 PHP 5.3 及更低版本存在无法从匿名函数内部访问本地对象上下文的限制。

It is not possible to use $this from anonymous function before PHP 5.4.0

你可以这样做:

$instance = $this;
$appointments = Label::with(['appointments' => function ($query) use ($instance) { // ... }

但是您无法访问 privateprotected 成员;它将被视为 public 访问。你真的需要 PHP 5.4 :)