在Laravel 5中,这是做什么的:$ this - > {$ var}

Leo*_*gal 0 php laravel

我在api端点中有以下代码,它检查要删除的模型上没有关系(并返回true以显示它正在使用中):

CONTROLLER

public function destroy(Group $group)
    {
        if ($group->inUse()) {
            return response(
                ['message' => 'This group cannot be deleted because it has either associated 
                catalogue items, users or organisations'],
                409
            );
        }

        $group->delete();
    }
Run Code Online (Sandbox Code Playgroud)

模型

public function inUse()
{
    $models = [
        'categories',
        'items',
        'organisations',
    ];

    foreach ($models as $model) {
        if (count($this->{$model}) > 0 ){
            return true;
        }
    }

    return false;
}
Run Code Online (Sandbox Code Playgroud)

我不完全理解的是我们检查每个模型的关系数量的地方: count($this->{$model})

我在php.net读到 $ this - > {$ var}是一个变量变量,但这不是这里的情况,循环的第一次运行会返回一个未定义的变量$ categories:

if($this->$categories) {
    //
}
Run Code Online (Sandbox Code Playgroud)

这是一个laravel功能还是特殊语法?我做了一个快速搜索,但没有任何结果,我可以看到.

提前致谢.

Rai*_*Dev 5

它的php语法,花括号用于动态调用对象属性,在你的情况下,这将被翻译为:

if (count($this->categories) > 0 ),if (count($this->items) > 0 )...