我使用一个构造仅获取请求变量一次,因为我需要在多个方法中使用它们,所以我不想重复代码。
public function __construct(Request $request)
{
$this->labelId = $request->label;
$this->statusId = $request->status;
$this->monthId = $request->month;
}
这适用于我的“标准” View ,但不适用于“标签 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) { // ... }
但是您无法访问私有(private)
或 protected
成员;它将被视为公共(public)访问。你确实需要 PHP 5.4 :)
关于php - Laravel 无法在匿名函数内使用 $this,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34957033/