The problem is that when using PHP7 the expected result is different from PHP5, see following example with $object2.
I think that the three methods are equivalent from each other, but it seems not to be true.
It seems that in PHP7 the shortcut used with $object2 return the type of variable instead of the value.
Is there some environment configuration of PHP7 that makes it behave like PHP5 with respect to this issue?
$array1 = array();
$array1["Key"] = "Value";
$object1 = new stdClass();
$key1 = $array1["Key"];
$object1->Stream = new stdClass();
$object1->Stream->$key1 = 5;
echo json_encode($object1);
$array2 = array();
$array2["Key"] = "Value";
$object2 = new stdClass();
$object2->Stream = new stdClass();
$object2->Stream->$array2["Key"] = 5;
echo json_encode($object2);
$array3 = array();
$array3 = "Value";
$object3 = new stdClass();
$object3->Stream = new stdClass();
$object3->Stream->$array3 = 5;
echo json_encode($object3);
Result in PHP5:
{"Stream":{"Value":5}}
{"Stream":{"Value":5}}
{"Stream":{"Value":5}}
Result in PHP7:
{"Stream":{"Value":5}}
{"Stream":{"Array":{"Key":5}}}
{"Stream":{"Value":5}}
尝试将其包装在{}中
$object2->Stream->{$array2["Key"]}
You can Store array index in varaible then use this variable in object
Try follwoing code
$array1 = array();
$array1["Key"] = "Value";
$object1 = new stdClass();
$key1 = $array1["Key"];
$object1->Stream = new stdClass();
$object1->Stream->$key1 = 5;
echo json_encode($object1);
$array2 = array();
$array2["Key"] = "Value";
$tmp = $array2["Key"];
$object2 = new stdClass();
$object2->Stream = new stdClass();
$object2->Stream->$tmp = 5;
echo json_encode($object2);
$array3 = array();
$array3 = "Value";
$object3 = new stdClass();
$object3->Stream = new stdClass();
$object3->Stream->$array3 = 5;
echo json_encode($object3);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.