原则 2:在 DateTimeType.php 中调用非对象上的成员函数 format() ...

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3378748/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 09:31:34  来源:igfitidea点击:

Doctrine 2: Call to a member function format() on a non-object ... in DateTimeType.php

phpdoctrine-ormdoctrine

提问by Jiew Meng

I have a DateTimefield:

我有一个DateTime领域:

/**
 * Date time posted
 * @Column(type="datetime")
 */
private $dtPosted;

which is set to a default value by using a LifeCycleCallback

使用 LifeCycleCallback 设置为默认值

/**
 * @PrePersist
 */
function onPrePersist() {
    // set default date
    $this->dtPosted = date('Y-m-d H:m:s');

I am getting the following error:

我收到以下错误:

Fatal error: Call to a member function format() on a non-object in D:\ResourceLibrary\Frameworks\Doctrine\lib\Doctrine\DBAL\Types\DateTimeType.php on line 46

致命错误:在第 46 行调用 D:\ResourceLibrary\Frameworks\Doctrine\lib\Doctrine\DBAL\Types\DateTimeType.php 中的非对象上的成员函数 format()

回答by romanb

The date()function returns a string. The datetimetype works with DateTimeobjects. So either change the mapping type to stringor use DateTimeobjects.

date()函数返回一个字符串。该datetime类型适用于DateTime对象。因此,要么将映射类型更改为string或使用DateTime对象。

回答by MediaVince

Try and use your setCreated with annotations for @ORM\PrePersist and setUpdated with annotations for @ORM\PrePersist and @ORM\PreUpdate methods as opposed to prePersist and preUpdate methods...

尝试使用带有@ORM\PrePersist 注释的setCreated 和带有@ORM\PrePersist 和@ORM\PreUpdate 方法注释的setUpdated,而不是prePersist 和preUpdate 方法......

/**
 * @ORM\PrePersist
 */
public function setCreated()
{
    $this->created = new \DateTime();
}

/**
 * @ORM\PrePersist
 * @ORM\PreUpdate
 */
public function setUpdated()
{
    $this->updated = new \DateTime();
}

回答by Adam Elsodaney

I came across a similar problem, but with a timefield, and this question and @romanb 's answer helped.

我遇到了类似的问题,但有一个time领域,这个问题和@romanb 的回答有帮助。

I was getting the following error, much like the one in the question.

我收到以下错误,很像问题中的错误。

Call to a member function format() on a non-object in 
... /vendor/doctrine/dbal/lib/Doctrine/DBAL/Types/TimeType.php on line 50

The solution was similar, for fields of the timedatatype, Doctrine will accept an instance of PHP's DateInterval

解决方案是类似的,对于time数据类型的字段,Doctrine 将接受 PHP 的一个实例DateInterval

$quizFixture1->setCompletionTime(\DateInterval::createFromDateString('743 seconds'));