我有一个User对象,该对象的受保护成员导致了PDO对象。
我正在使用Silex / Symfony,当我尝试登录时Symfony\Component\Security\Core\Authentication\Token\AbstractToken
会序列化该对象并给出异常,因为PDO对象无法序列化。
我尝试将成员设为 private ,但这无济于事。如果我在__sleep中取消设置属性,则不知道如何将其放回__wakeup中,因为该成员是通过在构造函数中传递来设置的。
我看过的示例通过静态查找返回了无法序列化的内容,但我试图避免这种情况。有任何想法吗?
最佳答案
您需要对用户对象实现Serializable
。
class User implements UserInterface, Serializable
{
// ...
public function serialize()
{
// see http://php.net/manual/en/serializable.serialize.php
return serialize(array(
$this->id,
$this->username,
$this->password
));
}
public function unserialize($serialized)
{
// see http://php.net/manual/en/serializable.unserialize.php
list ($this->id, $this->username, $this->password) = unserialize($serialized);
}
}
编辑
警告:仅回答问题“如何防止序列化打中某个成员”。如果您发现自己遇到类似的问题,则应重新考虑您在做什么。有关更多详细信息,请参见@Bryan Agee的答案。
关于php - PHP:如何防止序列化击中某个成员,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30471341/