我想从php对象类添加自定义属性

时间:2018-07-05 12:40:03

标签: php mysql

我想为每个对象添加新属性。我的代码如下所示:

 function getCitationDataofquotes($var1){
    $query = "SELECT `id`,`title`,`source`,`content`,`page`,`city`,`publisher` FROM `#__gpo_citations_quotes`";
    $query .= " WHERE `id`='" . $var1 . "'";
    if (!empty($query))
    {
        $some= array();
        $this->_db->setQuery($query);
        $data = $this->_db->loadObject();
        return $data; 

    }
 $value = $datapages->getCitationDataofquotes($var1);
 $getdataofcitation['citations'][] = $value;

然后我的返回数据输出如下

{id: "12091",
title: "Homicide Victims by Year and Jurisdiction, 1989–90 to 2010–12",
source: "Homicide in Australia: 2010–11 to 2011–12: National Homicide Monitoring Program report",
content: " ACT = Australian Capital Territory]",
page: "p. 37",
city: "Canberra",
publisher: "Australian Institute of Criminology"
},

{
id: "8901",
title: "test",
source: null,
content: "",
page: null,
city: null,
publisher: null
},

现在,我想为每个对象添加新属性。我想要每个对象的输出。

{ id: "8901",
 title: "test",
 source: null,
 content: "",
 page: null,
 city: null,
 publisher: null ,
 **new property: something**}

2 个答案:

答案 0 :(得分:0)

首先,您的$ query容易受到Sql注入的攻击。顺便说一句,有多种方法可以达到您想要的结果。例如,您可以改为在查询中添加属性:

SELECT 'some value' As `some_field` ...

如果要在php代码中添加它,可以按照@madalinivascu上面所说的动态添加它:

如果它是对象:

$myObject->myNewProperty = 'My new value'; 
# if it is dynamically and you don't know the name ...
$myObject->{"myNewProperty"} = 'My new value'; 

如果是数组:

$myArray['myNewProperty'] = 'My new value';

答案 1 :(得分:0)

当值返回带有数组的多个对象时更新此代码

   const stringData = JSON.stringify(jsonData);
      this.stepperForm.setValue({
        apps: new FormControl(''),
        params: new FormControl(stringData , SpecifyDetailsStepComponent.isValidJsonValidatorFn()),
      });
    }