Reputation: 18188
I would like to pass around a php class instance between PHP and JavaScript by using Ajax and jQuery.
I need to access data properties in JavaScript and execute methods in PHP. The following piece of code shows what I mean:
index.php
<?php require_once("php/foo.php") ?>
var bar = <?php echo json_encode(new foo()); ?>;
// do something with 'bar'
$.post("ajax/foo.ajax.php", { foo : bar }, function(data) {});
foo.ajax.php
require_once("php/foo.php);
if (isset($_POST["foo"]))
{
$bar = $_POST["foo"];
// do something with 'bar'
echo json_encode($bar);
}
Upvotes: 0
Views: 456
Reputation: 214
There really isn't a mechanism in PHP to accomplish that right now. You can use serialize and unserialize to retain object structure, and json_encode will pull all of the public properties out of your object, but json_decode will return it into a state of a StdObject (standard object) in PHP.
A workaround for this would be the iterate over the properties returned and reset them in your object.
Upvotes: 1