I have instantiated a class in my index.php
file. But then I use jQuery Ajax to call some PHP files, but they can't use my object that I created in the index.php
file.
How can I make it work? Because I don´t want to create new objects, because the one I created holds all the property values I want to use.
Use the session to save the object for the next page load.
Then in the next page that loads from AJAX
By using the PHP sessions you can save data across many pages for a certain user. For example, maybe each user has a shopping cart object that contains a list of items they want to buy. Since you are storing that data in THAT USERS session only - each user can have their own shopping cart object that is saved on each page!
If you don't want to move your object that is in your index.php, have your ajax make a request to index.php but add some extra parameters (post/get) that let your index.php know to process it as an ajax request and not return your normal web page html output.
Another option if you dont want to use sessions is to serialize your object and send it through a $_POST value in your AJAX call. Not the most elegant way to do it, but a good alternative if you don't want to use sessions.
See Object Serialization in the documentation for more informations.
You have not provided code, but what I guess is that you need to make your instantiated object global for other scripts to see it, example:
Now I want to use this object elsewhere, probably under some function or class, or any place where it is not getting recognized, so I will make this global with the global keyword and it will be available there as well:
Once you have the object, you can put it into the session and then utilize it in the Ajax script file.
mm, you should store in session,
$_SESSION["someobj"] = $myobj;
, and ensure that when you call the Ajax PHP file this includes the class necessary files which defines the class of$myobj
and any contained object in it.Could you be more specific? I can try.
This is how I create an object then assign it to a session variable:
This is how I access the object's members in my Ajax call PHP file:
Based on most of the answers here, referring to storing the object in $_SESSION, is it more efficient to store only the individual properties that need to be accessed in AJAX as opposed to the whole object, or does it not matter?
E.g.
vs
I know the OP is asking about accessing the entire object, but I guess my question pertains to if it's just a matter of only accessing certain properties of an object, and not needing to access methods of a class to alter the object once it's in AJAX.