1

I took a look into the source code of laravel and found the following code:

    $attributes = $this->addDateAttributesToArray(
        $attributes = $this->getArrayableAttributes()
    );

Source

as you can see, there are assignments to the $attributes variable. One of them is in the parameter list. Albeit this is valid syntax, its immediately overwritten by the "outer" assignment.

Why would someone write code like this? Is there a special behavior I am not aware of?

4

1 回答 1

1

正如您在评论中清楚地看到的那样。

如果属性是日期,我们将在将其转换为 DateTime / Carbon 实例后将其转换为字符串。这样我们将在访问属性与排列/ JSON 模型时获得一些一致的格式。

其次,这没有什么花哨的。这只是使程序可读的技术。

这是一个例子。

return new HttPStatus(301);
  • 你能告诉我上面给出的代码在做什么吗?

    也许你会在谷歌上搜索到 301 HTTP 状态代码,它告诉我们 301 Moved Permanently 用于永久 URL 重定向。

让我们看另一个例子。

json_decode($string, true);
  • 你能告诉我为什么我们要通过true.?

  • 它的目的是什么。?

如果你没有经验,你json_decode($string, true);会再次谷歌为什么我们必须通过一个truejson_decode()

让我们再举一个例子。

json_decode($string, $returnArray = true);

现在从上面的代码中我们可以清楚的了解到,如果我们通过true它会返回一个数组。$returnArray = true只是一个一次性变量,它增加了代码的可读性。

这也是同样的情况

// If an attribute is a date, we will cast it to a string after converting it
// to a DateTime / Carbon instance. This is so we will get some consistent
// formatting while accessing attributes vs. arraying / JSONing a model.
$attributes = $this->addDateAttributesToArray(
    $attributes = $this->getArrayableAttributes()
);

$attributes = $this->getArrayableAttributes()它只是一个一次性变量,它告诉我们正在传递属性,从而提高了代码的可读性。

希望这可以帮助。

于 2018-06-19T11:23:44.020 回答