在 Laravel 作業(yè)類中,其代碼如下圖所示。如果滿足條件,我想為我的對象分配一個屬性(保留不是數(shù)據(jù)庫上的列)。問題是我在構(gòu)造函數(shù)之外看不到該屬性。請問我做錯了什么?class SomeJob implements ShouldQueue{ private $length = 300; private $width; private $area; public function __construct() { $areas = Area::where('length', $this->length)->get()->each(function($area) { if($area->length === 300) { $area->reserve = ($area->length + 400); } }); $this->area = $areas; // *log has $area } public function handle() { $area = $this->area; logger($area); // *log does not have $area }}
4 回答

慕沐林林
TA貢獻2016條經(jīng)驗 獲得超9個贊
要訪問方法中的任何屬性,您必須顯式調(diào)用該方法,例如$sj = new someJob(); $sj->handle()
;. “Var 轉(zhuǎn)儲”類揭示其屬性,并且根據(jù)環(huán)境和可見性,某些屬性可能可見也可能不可見。當(dāng)一個類被實例化時,首先會自動調(diào)用構(gòu)造函數(shù),這就是為什么您可以“記錄”并查看您的類屬性的原因。在引擎蓋內(nèi),Laravel 在運行作業(yè)類時調(diào)用 handle 方法,但如果你手動測試它,你必須自己做。

桃花長相依
TA貢獻1860條經(jīng)驗 獲得超8個贊
您需要在函數(shù)外部定義屬性__construct()。目前,這些變量的范圍僅限于閉包內(nèi)可用__construct()。
class SomeJob implements ShouldQueue
{
protected $length;
protected $width;
protected $area;
public function __construct()
{
//...
- 4 回答
- 0 關(guān)注
- 169 瀏覽
添加回答
舉報
0/150
提交
取消