【问题标题】:Type error: Return value must be an instance, null returned类型错误:返回值必须是实例,返回null
【发布时间】:2017-04-22 15:57:24
【问题描述】:

我正在使用 php7 的类型提示。所以我有以下代码

class Uni
{
 /**
     * @var Student
     *
     * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Student")
     * @ORM\JoinColumn(nullable=false)
     */
    private $student;

    function _construct(){
        $this->student= new Student();
    }

    /**
     * Set student
     *
     * @param \AppBundle\Entity\Student $student
     *
     * @return Uni
     */
    public function setStudent (Student $student): Uni
    {
        $this->student= $student;

        return $this;
    }

    /**
     * Get student
     *
     * @return \AppBundle\Entity\Student
     */
    public function getStudent(): Student 
    {
        return $this->student;
    }

}

现在当我尝试为 Uni 加载新表单时,出现此错误

Type error: Return value of AppBundle\Entity\Uni::getStudent() must be an instance of AppBundle\Entity\Student, null returned 

我怎样才能摆脱这个错误?我找到了一个可以为空的解决方案,它需要 php 7.1。但现在我必须坚持使用 php 7.0。那么我该如何解决呢?

【问题讨论】:

    标签: php php-7 type-hinting


    【解决方案1】:

    您的构造函数中有错字,construct 之前必须有两个下划线。

    function __construct() {
        $this->student = new Student();
    }
    

    因此,创建对象时$studentnull

    【讨论】:

      猜你喜欢
      • 2021-05-02
      • 2018-07-24
      • 1970-01-01
      • 2022-12-03
      • 1970-01-01
      • 1970-01-01
      • 2019-07-18
      • 1970-01-01
      • 2021-10-25
      相关资源
      最近更新 更多