Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/257.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 实体中未定义的索引';s getter,即使索引是在constructor中定义的_Php_Arrays_Symfony_Doctrine Orm_Entity - Fatal编程技术网

Php 实体中未定义的索引';s getter,即使索引是在constructor中定义的

Php 实体中未定义的索引';s getter,即使索引是在constructor中定义的,php,arrays,symfony,doctrine-orm,entity,Php,Arrays,Symfony,Doctrine Orm,Entity,我有一个实体类,包含以下信息: class A { ... private $share_data; public function __construct() { $this->share_data = array( 'title' => null, 'text' => null, 'image' => null, 'tab_i

我有一个实体类,包含以下信息:

class A
{
    ...
    private $share_data;
    public function __construct()
    {
        $this->share_data = array(
            'title' => null,
            'text' => null,
            'image' => null,
            'tab_image' => null
        );
    }
    ...
    public function getTabImage()
    {
        return $this->share_data['tab_image'];
    }
当我使用Symfony的form builder构建表单时,我使用以下代码:

$builder->add('tab_image', 'text', array('required'=>false, 'mapped'=>true, 'label'=>'a.form.tab.image_url'))
因此,当我尝试运行代码时,会出现错误注意:未定义索引:tab\u image in…

我想这是因为在我的数据库中,我的列类型是json_数组(称为share_data),因此将调用setShareData。在数据库值中,json对象中仅定义了标题、文本和图像字段。因此,对象可能会被覆盖到一个没有tab_image键的数组中。我试图通过将setShareData更改为以下内容来解决此问题:

public function setShareData($shareData)
{
    // merge so that null values are default
    $this->share_data = array_merge($this->share_data, $shareData);

    return $this;
}
希望它能保留构造函数中设置的tab_索引键。但我仍然得到未定义的索引错误。没有设置tab_图像键时,有没有办法将其保持为空


我想解决这个问题,这样我就可以向array/json对象添加新的键,而不必检查每个getter中是否有isset。显然,新创建的对象会获得tab_图像键,但我希望这是向后兼容的。

如果您有输入错误,请尝试
\uu构造
,您缺少s

,那么您要从数据库中提取此实体吗

条令在水合对象时不调用构造函数。这有点神奇,但属性是直接设置的。事实上,在水合过程中也不会调用setSharedData

您可以侦听加载后生命周期事件()

做一些类似于:

private function getSharedDataTemplate()
{
    return array(
        'title' => null,
        'text' => null,
        'image' => null,
        'tab_image' => null
    );
}
public function __construct()
{
    // For new'ing objects
    $this->share_data = $this->getSharedDataTemplate();
}
/** @PostLoad */
public function doStuffOnPostLoad()
{
    // merge so that null values are default
    $this->share_data = array_merge($this->getSharedDataTemplate(), $this->share_data);
    return $this;
}

您还可以通过设置某种标志并始终检查数据是否需要合并来使其工作。但是生命周期方法会更干净。

这实际上只是一个输入错误,因此,它正确地在代码中
\u构造。@juuga我明白了,在数组\u合并之前打印\r($shareData)和打印\r($this->share\u data)会发生什么?好的,我不知道没有调用构造函数。谢谢