在db上插入的carbon对象和在php上打印的carbon对象之间的区别

4urapxun  于 2021-06-17  发布在  Mysql
关注(0)|答案(1)|浏览(384)

我有一个疑问,如果我在php中用carbon:now()我把它插入数据库,行显示“2018-12-26 14:56:00”,但如果我打印它,它会给我一个碳物体,为什么会发生这种情况?

t98cgbkg

t98cgbkg1#

查看源代码(简要)

/**
 * 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';

我知道魔法 __toString 方法在输出时调用,例如 echo 或者 print 但不是 var_dump , var_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 这个类被设计成在把它转换成字符串时输出它。
所以一旦你把它和我在源代码中找到的那一小段结合起来,一切都是有意义的。
您的输出方式不会将其转换为字符串
当它被转换成一个字符串时,它被设计成使用这种格式。
甚至连看都不看 toString 方法我敢打赌它包含如下内容:

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

事实上(经过一番挖掘)我们发现它存在于一种“特质”中

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

重写该行为(作为一个anon函数,或者作为对它自己的format方法的调用),在转换为字符串时返回什么格式。
我以前从没用过碳!!
干杯。
沙箱

相关问题