A. O.
A. O.

Reputation: 720

Set a variable property from an object in PHP

I have an "obj" object and a "str" string. How do i set the $str property from "obj"? This is my try:

$jsonStr = '{"foo":"bar","number":1}';
$jsonObj = json_decode($jsonStr);
$property = $_GET["prop"];
$jsonObj->$property = "value";
file_put_contents("OUT",json_encode($jsonObj));

It always outputs "{}"!

Note: Please sorry for bad english, i'm not a native english speaker.

EDIT: I've tried to var_dump() every single variable in the code.

so the error is in file_put_contents("OUT",json_encode($jsonObj)); ...

EDIT 2: I've found the error! In the real code, i had written

$jsonStr = '{"foo":"bar","number":1}';
$jsonObj = json_decode($jsonStr);
$property = $_GET["prop"];
$jsonObj->$property = "value";
file_put_contents("OUT",json_encode(      ---->$jsonStr<----- ERROR! ));

Thanks for helping!

Upvotes: 1

Views: 81

Answers (1)

A. O.
A. O.

Reputation: 720

Simply do

file_put_contents("OUT",json_encode($jsonObj));

instead of

file_put_contents("OUT",json_encode($jsonStr));

The code actually works! It was an spelling error.

Upvotes: 1

Related Questions