如何测试序列化变量?如果字符串没有序列化,不抛出E_NOTICE


How can I test for a serialized variable? Without throwing E_NOTICE if string is not serialized

我正在编写自己的var_dump以满足某些可能只适用于我并且有问题的要求。

代码检查对象、数组等,最后到达一个阶段,它认为剩下一个数字、字符串或布尔值。

当然,字符串实际上可以是一个序列化的变量,所以我想检查一下…

if (is_string($variable))
{
   // check if it is serialzed; if so, unserialize & dump as an array, '
   // with a suitable header indicating that it was serialized
   try
   {
      $old_error_level= error_reporting(E_ALL ^ E_NOTICE);
      $unserialized_varaible = @unserialize($variable);
      $result .= my_dump($unserialized_varaible, ... <some params>); // recursive call
      $old_error_level= error_reporting($old_error_level);
   }
   catch(Exception $e)    // Treat it as a string
   {
       $old_error_level= error_reporting($old_error_level);
       $result .= GetHtmlForSimpleVariable($variable, ... <some params>);
   }
}

但是,当我试图转储一个简单的,非序列化的字符串时,我得到的是

Problem type Notice "unserialize() 
  [<a href='function.unserialize'>function.unserialize</a>]:
  Error at offset 0 of 14 bytes" at line 362 in file my_dump.php<br><br>

Update:这里的要点是,当字符串不是序列化字符串时,我想要抑制E_NOTICE。我原以为@unserizlize()上的@会这样做,但是……

如果字符串被序列化,那么一切都很好。

当您尝试反序列化它时,如果它未被序列化,则返回false。它还返回一个E_NOTICE,这是输出的来源。

从手册:

如果传递的字符串不是不可序列化的,则返回FALSE和E_NOTICE发出

检查unserialize ===false的返回值