Jump to content

[SOLVED] Losing object after form submit


orumaan

Recommended Posts

Hi there, I feel a little silly asking this basic question but I can't seem to find the solution in any tutorials for learning object oriented php.  I am literally brand new to PHP so this explains not knowing.  :)

 

Anyway, I fully understand how classes work, what attirbutes are, what functions are and how to call them.  The problem I have is, I have a class which is called game saved in its own php file (game.php).  In another php file (index.php) I include that class, then I instantiate an object using $mygame = new game(); Fair enough. Now in index.php I have a form with an input text box and a submit button. The page submits to itself and reloads. I can check what values were posted, but my problem is I can't edit the attributes of the $mygame object because the page reloaded and the object seems to have been lost during the reload.  By the way, I took care of making sure that a new $mygame object is not instantiated if the page loaded with values submitted from the form.

 

Is there a way to get round this?

 

Thanks.

Link to comment
https://forums.phpfreaks.com/topic/116390-solved-losing-object-after-form-submit/
Share on other sites

You will need to also submit the data from $mygame to the second page.

You can do it with hidden form objects or via sessions.

 

Thanks unkwntech.  I had an idea that this may be necessary, but of course if the object has many attributes, it involves a good few lines of code to set hidden fields before submission, and on page load to read them back and re-add them as attribute values to a newly instantiated $mygame object.

 

It's also a little bit more complex (well at least for me) because some of those attributes are actually arrays rather than simple string or integer values.

 

In any case I was hoping there would be an easy way of just passing a complete object so to speak.  I'll have a look at maintaining session information.  Thanks again.

PHP is stateless so it will not keep the objects in memory once you refresh the page, as unkwntech suggested you can serialize the object and put it in session or file and use on other pages.

 

Thanks samshel, the serialise method seems exactly what I need. :)

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.