Check if a variable is serializable

I am looking for an elegant way to test if a variable is serializable. For example, array( function() {} ) will not be serialized.

I am currently using the code below, but it seems like this is a rather suboptimal way to do this.

 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) 
+6
source share
2 answers

An 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 the 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]); } 
+6
source

Late answer, but ...

According to PHP documentation , resource type vars cannot be serialized. However, at least in PHP 5.4, trying to serialize a resource does not cause any errors.

I think the best approach would be to test for closure and resources without try / catch:

 $resource = fopen('composer.json', 'r'); $closure = function() { return 'bla'; }; $string = 'string'; function isSerializable($var) { if (is_resource($var)) { return false; } else if ($var instanceof Closure) { return false; } else { return true; } } var_dump(isSerializable($resource)); var_dump(isSerializable($closure)); var_dump(isSerializable($string)); 

Outputs:

 boolean false boolean false boolean true 
0
source

Source: https://habr.com/ru/post/886599/


All Articles