碳对象在什么时候转向拉拉维尔(Laravel)中的字符串?

发布于 2025-01-30 01:57:38 字数 371 浏览 5 评论 0原文

我想用Laravel编写类似于碳日期的铸件,我意识到,当碳日期传递到前端或叶片组件时,碳日期已转换为字符串。

我一直在没有运气的情况下挖掘源代码,有人知道这是如何工作的吗?

我的理解是,__tostring()方法在某个时候在碳对象上调用,但不知道在哪里。

一个例子是:


$user = User::first();
// here created_at is a Carbon instance

return response()->with(['created_at' => $user->created_at]);
//once this is on blade created_at is a string

Looking to write a cast similar to Carbon dates with Laravel, I realized that a Carbon date is converted to a string when passed over to the front-end or blade component.

I have been digging the source code with no luck, does anybody know how this works?

My understanding is that the __toString() method is called on the carbon object at some point but don't know where.

an example would be:


$user = User::first();
// here created_at is a Carbon instance

return response()->with(['created_at' => $user->created_at]);
//once this is on blade created_at is a string

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

万劫不复 2025-02-06 01:57:38

因此,经过更多的挖掘发现JSON_ENCODE()对此负责。

因此,如果您是json_encode碳对象,则输出为字符串。响应在Laravel的响应过程中转换为JSON。

如果您想通过响应传递PHP对象,并且只想接收一个字符串而不是一个对象,则可以使用jsonserializable

class MyClass implements JsonSerializable
{
 public function jsonSerialize(): string
 {
   return 'something';
 }
}

$class = new MyClass()
json_encode($class) // "'something'"

希望这对将来有帮助

So after more digging found out that json_encode() is responsible for this.

Therefore if you a json_encode a carbon object, the output is a string. The responses are converted to JSON in laravel's ResponseFactory.

If you would like to pass a PHP object through a response and would like to only receive a string instead of an object you can utilize JsonSerializable

class MyClass implements JsonSerializable
{
 public function jsonSerialize(): string
 {
   return 'something';
 }
}

$class = new MyClass()
json_encode($class) // "'something'"

Hope this helps someone in the future

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文