Documentation

Introduction - Zend_Serializer

Introduction

Zend_Serializer provides an adapter based interface to simply generate storable representation of PHP types by different facilities, and recover.

Example #1 Using Zend_Serializer dynamic interface

To instantiate a serializer you should use the factory method with the name of the adapter:

  1. $serializer = Zend_Serializer::factory('PhpSerialize');
  2. // Now $serializer is an instance of Zend_Serializer_Adapter_AdapterInterface,
  3. // specifically Zend_Serializer_Adapter_PhpSerialize
  4.  
  5. try {
  6.     $serialized = $serializer->serialize($data);
  7.     // now $serialized is a string
  8.  
  9.     $unserialized = $serializer->unserialize($serialized);
  10.     // now $data == $unserialized
  11. } catch (Zend_Serializer_Exception $e) {
  12.     echo $e;
  13. }

The method serialize() generates a storable string. To regenerate this serialized data you can simply call the method unserialize().

Any time an error is encountered serializing or unserializing, Zend_Serializer will throw a Zend_Serializer_Exception.

To configure a given serializer adapter, you can optionally add an array or an instance of Zend_Config to the factory() or to the serialize() and unserialize() methods:

  1. $serializer = Zend_Serializer::factory('Wddx', array(
  2.     'comment' => 'serialized by Zend_Serializer',
  3. ));
  4.  
  5. try {
  6.     $serialized = $serializer->serialize(
  7.         $data,
  8.         array('comment' => 'change comment')
  9.     );
  10.  
  11.     $unserialized = $serializer->unserialize(
  12.         $serialized,
  13.         array(/* options for unserialize */)
  14.     );
  15. } catch (Zend_Serializer_Exception $e) {
  16.     echo $e;
  17. }

Options passed to the factory() are valid for the instantiated object. You can change these options using the setOption(s) method. To change one or more options only for a single call, pass them as the second argument to either the serialize() or unserialize() method.

Example #2 Using the Zend_Serializer static interface

You can register a specific serializer adapter as a default serialization adapter for use with Zend_Serializer. By default, the PhpSerialize adapter will be registered, but you can change this option using the setDefaultAdapter() static method.

  1. Zend_Serializer::setDefaultAdapter('PhpSerialize', $options);
  2. // or
  3. $serializer = Zend_Serializer::factory('PhpSerialize', $options);
  4. Zend_Serializer::setDefaultAdapter($serializer);
  5.  
  6. try {
  7.     $serialized   = Zend_Serializer::serialize($data, $options);
  8.     $unserialized = Zend_Serializer::unserialize($serialized, $options);
  9. } catch (Zend_Serializer_Exception $e) {
  10.     echo $e;
  11. }

Copyright

© 2006-2021 by Zend by Perforce. Made with by awesome contributors.

This website is built using zend-expressive and it runs on PHP 7.

Contacts