Carbon对象插入DB并打印在PHP上的区别

问题描述 投票:-1回答:1

[我有一个疑问,如果我用Carbon:now()在PHP中创建一个Carbon对象,然后将其插入数据库中,则该行将显示'2018-12-26 14:56:00',但是如果我将其打印出来,我是一个碳物体,为什么会发生?

php mysql database php-carbon
1个回答
1
投票

简短地查看源代码

/**
 * Default format to use for __toString method when type juggling occurs.
 *
 * @var string
 */
public const DEFAULT_TO_STRING_FORMAT = 'Y-m-d H:i:s';

而且我知道在输出诸如__toStringecho而不是printvar_dumpvar_export时会调用魔术print_r方法。但这实际上会影响将对象强制转换为字符串(实际上并不依赖于输出)。只是使用var_dump和“ friends”之类的东西不会首先将其转换为字符串。

例如,我们可以很容易地“证明”

class foo{

    public function __toString(){
        return "foo";
    }
}

$f = new foo;

print_r($f);

echo "\n";

echo $f;

echo "\n\n";

print_r((string)$f);

输出

foo Object //output from print_r
(
) 

foo //output from echo

foo //output from casting to string and print_r

所以回答您的问题,那是因为您使用的不是echo,而是该类旨在将其转换为字符串时将其输出。

因此,一旦将其与我在源代码中找到的那段小片段结合起来,一切都说得通。

    1. 您以不将其转换为字符串的方式输出它
    1. 当将其转换为字符串时,将使用该格式。

并且甚至不用看toString方法就可以打赌它包含这样的内容:

public function __toString(){
    return $this->format(static::DEFAULT_TO_STRING_FORMAT); //or self::
} 

实际上(经过一番挖掘之后,我们在“特质” Here中找到了它

public function __toString()
{
    $format = $this->localToStringFormat ?? static::$toStringFormat;
    return $format instanceof Closure
        ? $format($this)
        : $this->format($format ?: (
            defined('static::DEFAULT_TO_STRING_FORMAT')
                ? static::DEFAULT_TO_STRING_FORMAT
                : CarbonInterface::DEFAULT_TO_STRING_FORMAT
        ));
}

我也可以告诉(通过观察)您可以设置以下2个之一:

 $this->localToStringFormat
 static::$toStringFormat

要覆盖转换为字符串时返回的格式,以覆盖该行为(作为匿名函数或对其自身格式方法的调用。)>

而且我以前从未用过碳!!

干杯。

sandbox

© www.soinside.com 2019 - 2024. All rights reserved.