Can anyone explain why the property of the $json object works in the database query when first assigned to a local variable, but throws a string conversion error if used directly? Thanks!
<?php
class Order {
protected $json;
public function __construct($json) {
$this->json = $json;
}
public function createOrder() {
$email = $this->json->email;
//Works
$sql = "INSERT INTO orders SET email='$email'";
// Doesn't work -- Object of class stdClass could not be converted to string
$sql = "INSERT INTO orders SET email='$this->json->email'";
...
}
}
?>
Two problems:
a) PHP's stdClass has no magic __toString() method, so there's no way for a stdClass to be used inside a string.
b) PHP's "
-quoted string parser isn't greedy, so your
$sql = "INSERT INTO orders SET email='$this->json->email'";
is parsed/executed as the equivalent of:
$sql = "INSERT INTO orders SET email='" . $this->json . "->email'";
which is where your error message is coming from. $this->json
is an object, with no __toString() magic method, therefore the warning.
If you want to use a multi-dimensional object in a "
-quoted string, you have to use the {}
-extended string syntax:
$sql = "INSERT INTO orders SET email='{$this->json->email}'";
^------------------^
which forces PHP to treat everything inside the {}
as a single unit.
The same holds for arrays:
$foo[1][2] = 3;
echo "$foo[1][2]";
is executed as:
echo $foo[1] . "[2]";
and gives you
Array[2]
as the output - arrays in string context are the literal word "Array". Using {}
makes it work as expected:
echo "{$foo[1][2]}";
outputs 3
.