Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 786
Kendall Hopkins Avatar asked Apr 25 '11 04:04

Kendall Hopkins


People also ask

How do you determine if the given object is serializable?

You can determine whether an object is serializable at run time by retrieving the value of the IsSerializable property of a Type object that represents that object's type.

How do you check if a class is serializable?

If you are curious to know if a Java Standard Class is serializable or not, check the documentation for the class. The test is simple: If the class implements java. io. Serializable, then it is serializable; otherwise, it's not.

How do you avoid variables to serialize?

You can prevent member variables from being serialized by marking them with the NonSerialized attribute as follows. If possible, make an object that could contain security-sensitive data nonserializable. If the object must be serialized, apply the NonSerialized attribute to specific fields that store sensitive data.

How check data is serialized or not in PHP?

$data = @unserialize($str); if($data !== false || $str === 'b:0;') echo 'ok'; else echo "not ok"; Correctly handles the case of serialize(false) . :) Show activity on this post.


1 Answers

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]);
}
like image 122
luka8088 Avatar answered Oct 12 '22 23:10

luka8088