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)
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.
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.
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.
$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.
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]);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With