I have an array of php objects. Inside a javascript function I want to access attributes of an object in the array. If I json_encode
the whole array it shows these attributes are undefined
. How can I do this. I new to PHP.
PHP Code:
$_SESSION['objArray'] = $objArray;
Javascript Code:
const objArray = <?php echo json_encode(($_SESSION['objArray'])) ?>;
Advertisement
Answer
You certainly need to encode your array to JSON so it can be usable by a JavaScript client.
As you mentioned, you have instances of particular classes in your array, so simple JSON encoding won’t work for sure.
Here, PHP comes with the JsonSerializable
interface. You will have to implement this interface on your classes. Let’s take a Foo
example:
class Foo implements JsonSerializable { private $thing; public function __construct($thing) { $this->thing = $thing; } public function jsonSerialize() { return [ 'thing' => $this->thing, ]; } }
Here is an example of the above code snippet. As you can see, now you can create an instance of Foo
, embed it into an array or whatever, and JSON-encode it with your own representation:
$foo = new Foo('something'); echo json_encode(['foo' => $foo]); // {"foo": {"thing": "something"}}
Outputting this into an inline JavaScript block would work similar to what you wrote:
<script type="application/javascript"> const obj = "<?php echo json_encode(($_SESSION['objArray'])) ?>;"; </script>