gpt4 book ai didi

php - Symfony 3 类的对象无法转换为字符串

转载 作者:行者123 更新时间:2023-12-04 19:04:26 24 4
gpt4 key购买 nike

我有这个地址表格。一切都按预期工作,直到我为城市添加了一个下拉选择字段。当我尝试保存表单时出现此错误:

Catchable Fatal Error: Object of class AppBundle\Entity\Address could not be converted to string

文档说 EntityType 字段旨在从 Doctrine 实体加载选项。

这是表格:

 $builder
->add('cities', EntityType::class, array(
'class' => \AppBundle\Entity\Cities::class,
'choice_label' => 'cityname',
'choice_value' => 'cityid')
)

这是我的实体

 /**
* @var string
*
* @ORM\Column(name="cities", type="string", length=55, nullable=false)
*/
private $cities;

和 setter/getter:

 /**
* Set cities
*
* @param string $cities
*
* @return Address
*/
public function setCities($cities)
{
$this->cities = $cities;

return $this;
}

/**
* Get cities
*
* @return string
*/
public function getCities()
{
return $this->cities;
}

我还添加了这个:

public function __toString() {
return $this->getCities();
}

得到了这样的结果:

Catchable Fatal Error: Method AppBundle\Entity\Address::__toString() must return a string value

最佳答案

你应该为你的实体实现 __toString() 方法:

__toString() allows a class to decide how it will react when it is treated like a string. For example, what echo $obj; will print. This method must return a string, as otherwise a fatal E_RECOVERABLE_ERROR level error is emitted.

例如,您可以编写如下代码来将您的类表示为字符串:

public function __toString() {
return $this->getCities();
}

关于这个魔术方法的更多信息here .

关于php - Symfony 3 类的对象无法转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47479268/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com