13.09.2016 Views

PHP and MySQL Web Development 4th Ed-tqw-_darksiderg

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Serializing Variables <strong>and</strong> Objects<br />

527<br />

Serialization has decreased in usefulness since the introduction of session control.<br />

Serializing data is principally used for the types of things you would now use session<br />

control for. In fact, the session control functions serialize session variables to store them<br />

between HTTP requests.<br />

However, you might still want to store a <strong>PHP</strong> array or object in a file or database.<br />

If you do, you need to know how to use these two functions: serialize() <strong>and</strong><br />

unserialize().<br />

You can call the serialize() function as follows:<br />

$serial_object = serialize($my_object);<br />

If you want to know what the serialization actually does, look at what is returned from<br />

serialize().This line turns the contents of an object or array into a string.<br />

For example, you can look at the output of running serialize() on a simple<br />

employee object, defined <strong>and</strong> instantiated thus:<br />

class employee<br />

{<br />

var $name;<br />

var $employee_id;<br />

}<br />

$this_emp = new employee;<br />

$this_emp->name = ‘Fred’;<br />

$this_emp->employee_id = 5324;<br />

If you serialize this <strong>and</strong> echo it to the browser, the output is<br />

O:8:”employee”:2:{s:4:”name”;s:4:”Fred”;s:11:”employee_id”;i:5324;}<br />

You can easily see the relationship between the original object data here <strong>and</strong> the serialized<br />

data.<br />

Because the serialized data is just text, you can write it to a database or whatever you<br />

like. Be aware that you should use mysql_real_escape_string() on any text data<br />

before writing it to a database to escape any special characters.You can see the need for<br />

this by noting the quotation marks in the previous serialized string.<br />

To get the object back, call unserialize():<br />

$new_object = unserialize($serial_object);<br />

Another point to note when serializing classes or using them as session variables:<br />

<strong>PHP</strong> needs to know the structure of a class before it can reinstantiate the class.<br />

Therefore, you need to include the class definition file before calling session_start()<br />

or unserialize().

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!