在 laravel 的 DB::transaction 中,为外部变量赋值

更新日期: 2018-07-30 阅读次数: 7527 分类: Laravel

例如,我想在 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

关于作者 🌱

我是来自山东烟台的一名开发者,有敢兴趣的话题,或者软件开发需求,欢迎加微信 zhongwei 聊聊, 查看更多联系方式

谈笑风生

foo

/** @test */
    public function test_transactio(){
        $user = create(User::class);

        \DB::transaction(function() use($user) {
            $user->name = 'foo';
        });

        $this->assertEquals($user->name, 'foo');
    }

测试成功啊!