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.
$_GET[“prop”] is “foo”
$jsonObj actually IS object(stdClass)#1 (1) {[“foo”]:”value”, [“number”]:1}, 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!


Source: oop

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.