我有一个拼写错误的类存储在MemCached中.这是一个例子:
class Person { public $n1ame; }
echo serialize(new Person());
Run Code Online (Sandbox Code Playgroud)
我在下一个代码版本中修复了拼写错误:
class Person { public $name; }
var_dump(unserialize($previousSerializedPersion));
Run Code Online (Sandbox Code Playgroud)
但这是发生的事情:PHP隐式地将未存在的字段添加到我的对象:
object(Person)#1 (2) {
["name"]=>
NULL
["n1ame"]=>
NULL
}
Run Code Online (Sandbox Code Playgroud)
我的人有额外的数据字段.我所期待的是一个例外.
有没有办法实现这一目标?
三点建议:
1.)在调用unserialize()之前,对序列化数据字符串执行手动字符串转换以更正它.
O:6:"Person":1:{s:5:"n1ame";N;}
Run Code Online (Sandbox Code Playgroud)
如果s:5是n1ame原始序列化中属性的字符长度,则需要将其更改s:4为将其还原为name,s对于字符串数据类型,数字是文本值的长度,在本例中为属性键.
O:6:"Person":1:{s:4:"name";N;}
Run Code Online (Sandbox Code Playgroud)
你可以试试
unserialize( str_replace( 's:5:"n1ame"', 's:4:"name"', $previousSerializedPersion ) );
Run Code Online (Sandbox Code Playgroud)
2.)另一个解决方案是__wakup()函数来纠正您的数据.这个函数在序列化之后但在分配和使用之前在你的对象上运行,这可能是一个"更好"的解决方案,因为它在代码中干净利落.
class Person
{
public $name;
public function __wakeup()
{
if( property_exists( $this, 'n1ame' ) )
{
$this->name = $this->n1ame;
unset( $this->n1ame );
}
}
}
unserialize('O:6:"Person":1:{s:5:"n1ame";s:4:"mark";}');
Run Code Online (Sandbox Code Playgroud)
3.)使用相同的__wakup()概念但抛出异常.
class Person
{
public $name;
public function __wakeup()
{
if( property_exists( $this, 'n1ame' ) )
{
throw new Exception('oh no this data is bad');
}
}
}
unserialize('O:6:"Person":1:{s:5:"n1ame";s:4:"mark";}');
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
69 次 |
| 最近记录: |