phpserializationclosures

Test if a variable is serializable


I'm looking for an elegant way of testing if a variable is serializable. For example array( function() {} ) will fail to serialize.

I'm currently using the code below, but it seems to be a rather non-optimal way of doing it.

function isSerializable( $var )
{
    try {
        serialize( $var );
        return TRUE;
    } catch( Exception $e ) {
        return FALSE;
    }
}

var_dump( isSerializable( array() ) );                // bool(true)
var_dump( isSerializable( function() {} ) );          // bool(false)
var_dump( isSerializable( array( function() {} ) ) ); // bool(false)

Solution

  • The alternative could be:

    function isSerializable ($value) {
      $return = true;
      $arr = array($value);
    
      array_walk_recursive($arr, function ($element) use (&$return) {
        if (is_object($element) && get_class($element) == 'Closure') {
          $return = false;
        }
      });
    
      return $return;
    }
    

    But from comments I think this is what you are looking for:

    function mySerialize ($value) {
      $arr = array($value);
    
      array_walk_recursive($arr, function (&$element) {
    
        # do some special stuff (serialize closure) ...
        if (is_object($element) && get_class($element) == 'Closure') {
          $serializableClosure = new SerializableClosure($element);
          $element = $serializableClosure->serialize();
        }
    
      });
    
      return serialize($arr[0]);
    }