1

I recently wrote a PHP wrapper class for a new API we are using and have been asked to setup a demo which makes use of it. Certain features can be called directly from PHP, however things such as performing actions on button clicks requires I make use of JS/AJAX.

As I already have an instance of the object in my main PHP file, can I pass this as a parameter to JS and then pass it through Ajax to my handler or is it necessary to establish two separate instances?

3
  • Is this really necessary? You should create a new instance by passing relevant data which you can work with. Or explain what you want to achieve Commented Jan 27, 2015 at 17:12
  • 3
    PHP and JavaScript are living in 2 differents "environnements", you can pass plain old values from one world to the other one (integer, strings, boolean, array), but AFAIK you can't pass object reference. Additionnaly, for each call to a PHP page, a new context is created, which means you can't share a reference to an object between 2 calls to your PHP file (JavaScript is not related to this in any way) Commented Jan 27, 2015 at 17:14
  • 4
    json serialization is the only thing that comes to my mind... And yes, it's an other instance with the same values Commented Jan 27, 2015 at 17:15

1 Answer 1

3

The closest thing to doing what you want that I can think of would be copying the PHP object to a JavaScript variable via json_encode and then passing that variable back to your PHP code during the AJAX event via the data parameter. PHP code doesn't persist in the way that you seem to be describing - once a page has been requested by a browser, your PHP code for that page is done, there are no variables persisted by the server after that point.

Sign up to request clarification or add additional context in comments.

3 Comments

One analogy I've used to help people understand is that the PHP processor is like a student doing homework; the "problem" is the PHP file / code. The "solution" is the generated HTML put out based on any given parameters or "solve for X". The key thing: As soon as the student gives you the answer, he throws away all the scratch-work he was writing as he came up with it. (Doing otherwise would be a massive memory problem for a decent-size server)
That's a great analogy. I'll have to remember that!
That is great and thank you for the answer! I think for simplicity sake I will just move all API related PHP code to the handler and use the main page to send commands via AJAX.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.