[英]Simple PHP7.0 class incorrectly serialized
我正在嘗試在PHP7.0中序列化一組簡單對象,但是由於某種原因,它無法正常工作。 這是var_dump
對象數組:
array (size=3)
0 =>
object(My\Bundle\Entity\Role)[504]
protected 'id' => int 2
protected 'role' => string 'ROLE_LDAP_CHECKIN_APP_ADMIN' (length=27)
1 =>
object(My\Bundle\Entity\Role)[506]
protected 'id' => int 3
protected 'role' => string 'ROLE_LDAP_CHECKIN_APP_USER' (length=26)
2 =>
object(My\Bundle\Entity\Role)[507]
protected 'id' => int 1
protected 'role' => string 'ROLE_USER' (length=9)
這將輸出以下序列化的字符串:
a:3:{i:0;r:18;i:1;r:22;i:2;r:26;}
如果我反序列化該字符串,則只會收到以下錯誤:
Notice: unserialize(): Error at offset 14 of 33 bytes
該類實現\\Serializiable
:
namespace My\Bundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\Role\RoleInterface;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Role Entity
*
* @ORM\Entity
* @ORM\Table( name="role" )
*
*/
class Role implements \Serializable
{
/**
* @ORM\Id
* @ORM\Column(type="integer", name="id")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @ORM\Column(type="string", name="role", unique=true, length=255)
* @Assert\NotBlank()
*/
protected $role;
/**
* Populate the role field
* @param string $role ROLE_FOO etc
*/
public function __construct($role)
{
$this->role = $role;
}
/**
* Return the id field.
*
* @return string
*/
public function getId()
{
return $this->id;
}
/**
* Set the role field
*
* @param $role
*/
public function setRole($role)
{
$this->role = $role;
}
/**
* Return the role field.
* @return string
*/
public function getRole()
{
return $this->role;
}
/**
* Return the role field.
* @return string
*/
public function __toString()
{
return (string) $this->role;
}
public function serialize()
{
return serialize(array($this->id, $this->role));
}
public function unserialize($serialized)
{
list($this->id, $this->role) = unserialize($serialized);
}
}
我可以確認正在加載該類。
編輯:根據http://www.phpinternalsbook.com/classes_objects/serialization.html ,序列化字符串中的'r'
條目代表“引用”,這意味着該條目只是一個引用/指向其他某個條目的指針在數組或對象中。 顯然,對第18、22和26條目的引用是沒有意義的。 這是PHP錯誤嗎?
我在問題寫作中沒有提到這一點,但是我在包裝類的serialize
化函數內部調用了序列serialize
函數。 換句話說,一個子類具有一個serialize
函數,在該serialize
函數中它稱為parent::serialize
,而我試圖在該嵌套的父項的serialize
函數內部序列化我的數組。 盡管不是未定義的行為,但這是PHP中的一個已知錯誤(是的,有時實際上這不是您的錯)。 該錯誤在此處列出: https : //bugs.php.net/bug.php?id=66052&edit=1
錯誤報告的一些摘錄:
當前的序列化格式未指定值id,而是依賴於數據開頭的計數。 雖然這對於“標准”序列化工作正常,但是當將自定義序列化(通過Serializable)放入組合中時,它會嚴重中斷。
...和...
此錯誤的影響是兩件事之一:
- 這些值只是指向錯誤的變量。 很難調試,並且對不熟悉序列化格式的任何人都造成混亂。
- 值指向不存在的值(-1或最大+1)。 這將導致錯誤,該錯誤將字節偏移報告到發生錯誤的序列化數據中。
這解釋了為什么問題中顯示的序列化字符串中的引用被破壞了。 除了手動拉平所有序列化調用外,我不知道該如何解決這個問題,我很震驚,尚未開發PHP的優秀專家對其進行了修復。 無論如何,如果您看到關於字符串/緩沖區字節偏移的看似莫名其妙的錯誤消息,請確保您沒有在執行自定義嵌套序列化。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.