例如,我想在 laravel 的事務中,對某個外部變量賦值,然后在后續的邏輯中判斷該變量的屬性
$user = null; // init DB::transaction(function() use($user) { // do something with user }); // check user if ($user->name) { // bla, bla }
這樣會報錯
Trying to get property of non-object at
也就是說,在 PHP 中,即使是對象也不會默認采用引用的方式傳參。
需要修改為
DB::transaction(function() use(&$user) { // do something with user }); // check user
果然,我還是個 PHP 初學者。。。
參考
https://stackoverflow.com/questions/31059540/laravel-get-variable-from-a-db-transaction-closure
