Kevin Lindmark
Kevin Lindmark

Reputation: 1257

php string to object varible - replacing name of an object

Objective to replace part of an object name. Get an error with the code below. Guessing the str_replace needs to be in another format?

foreach($data as $i => $item) {
   if(strpos($i, 'SIEcat134') !== false){
       $data-> str_replace("SIEcat134","newname",$i) = $data->$i; 
       unset($data->$i);
    } 

}

Object example (contains many more rows)

stdClass Object
(
    [SIEcat134analys] => test
    [SIEcat134avst1] => test2
    [SIEcat134avstbelcy1] => 469 915
    [SIEcat134avstref1] => 19.1
    [SIEcat135analys] => test
    [SIEcat135avst1] => test2
    [SIEcat135avstbelcy1] => 469 915
    [SIEcat135avstref1] => 19.1
 etc
etc
}

Upvotes: 0

Views: 31

Answers (1)

Barmar
Barmar

Reputation: 781088

If you want to use an expression as a dynamic property name, you have to wrap it in {}.

$data->{str_replace("SIEcat134","newname",$i)} = $data->$i; 

You can only leave out the braces when the expression is just a simple variable, as in $data->$i.

Upvotes: 1

Related Questions