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

4c8rllxm  于 2021-06-20  发布在  Mysql
关注(0)|答案(2)|浏览(468)

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

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**}
t9eec4r0

t9eec4r01#

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

$value[] = $datapages->getCitationDataofquotes($var1);

                for($i=0; $i<count($value); $i++) 
                {
                    $value[$i]->newprop = 'new content';
                }
5hcedyr0

5hcedyr02#

首先,您的$查询易受sql注入攻击。顺便说一句,有多种方法可以达到你想要的结果。e、 g您可以在查询中添加属性:

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';

相关问题