PHP Object Passing Writer #1, 2010-04-16 Using objects in PHP doesn’t have to be a one-way-street. PHP objects are very similar to any other server side language in that they can run functions for you, return values, and perform just about any needed task that you can write, but they can also be passed around within a session. If you program in JSP or .NET, you’ll be thinking “so what?” But if you only dabble in PHP you may not have ever tried this. Serialize The main requirement for passing objects is the “serialize” method. A definition of serialize is: To convert an object into a sequence of bytes that can later be converted back into an object with equivalent properties Basically, when you serialize an object, you are making it turn into a more tangible glob of information. A parallel would be like this: someone’s spoken word is like unserialized data. If I write down their words on paper, it is like serializing it so that I can mail it somewhere else. When someone receives it they can read it aloud, thereby making it unserialized again. The Code First create a new class that you will be using to hold your data. Name the file db.php. <?php class DB{ function __construct(){ //optional } function SetX($value){ $this->x = $value; } function GetX(){ return $this->x; } } ?> One of the most important things to remember in this file is the usage of the keyword “this”. You must refer to your variables using $this->variableName. If you don’t then it will not affect the values that get serialized. It will only affect the values within the function and the values will disappear at the end of the function. If you want a value to persist then set it using $this->x and get it using $this->x. Next, create the first page that will implement the class just made above. Call it test.php, if you want. <?php session_start(); // this is whatever you named the file above. include_once("db.php"); // make an object out of it. $db = new DB(); // call a function. This function sets a value within the object. $db->SetX(1000); ?> <a href="test2.php"> Link to next page </a> x = <?php echo $db->GetX(); ?> <?php $_SESSION['db'] = serialize($db); // Just so you can see what it looks like: echo "<h4>Serialized Data</h4>"; echo ( $_SESSION['db'] . "<hr>"); ?> Then create the second page that will be using the serialized object. Call it test2.php <?php session_start(); // required to include it again so it has a definition of the class include_once("db.php"); // unserialize puts it back to a usable form $db = unserialize($_SESSION['db']); ?> x = <?php // call your getter function and the value is retained from the previous page echo $db->GetX(); ?> You’re Done! Well, actually you’ve just begun. But that’s how it is done. PHP Programming objectsphp