2013-12-13 52 views
0

我遇到了一個奇怪的問題,其中如果我嘗試序列化同一類的對象數組,該類已實現Serializable接口,並在可序列化接口中返回序列化的實例在另一個類中,第一對之後的數組項被認爲是遞歸的。其中值實現Serializable的PHP數組序列化

下面是測試情況:

<?php 

class HelloWorld implements Serializable { 
    public $test; 

    public function __construct($str) 
    { 
     $this->test = $str; 
    } 

    public function serialize() 
    { 
     $simple = null; 
     $simple = new Simple(); 
     $simple->test = $this->test; 
     return serialize($simple); 
    } 

    public function unserialize($str) 
    { 
     $simple = unserialize($str); 
     $this->test = $simple->test; 
    } 
} 

class Simple 
{ 
    public $test; 
} 

$list = array(
    new HelloWorld('str1'), 
    new HelloWorld('str2'), 
    new HelloWorld('str3'), 
    new HelloWorld('str4'), 
    new HelloWorld('str5'), 
    new HelloWorld('str6'), 
    new HelloWorld('str7'), 
    new HelloWorld('str8'), 
    new HelloWorld('str9'), 
); 

$str = serialize($list); 
echo $str . "\n"; 

// var_dump(unserialize($str)); 

取消對最後一行,並享受一個PHP分段錯誤。

有誰知道這是爲什麼或如何解決它?如果在HelloWorld::serialize()中序列化的是數組或原始值,這似乎不成問題。

更新:

這裏是從上面的代碼的輸出:

a:9:{i:0;C:10:"HelloWorld":39:{O:6:"Simple":1:{s:4:"test";s:4:"str1";}}i:1;C:10:"HelloWorld":4:{r:3;}i:2;C:10:"HelloWorld":4:{r:3;}i:3;C:10:"HelloWorld":4:{r:3;}i:4;C:10:"HelloWorld":4:{r:3;}i:5;C:10:"HelloWorld":4:{r:3;}i:6;C:10:"HelloWorld":4:{r:3;}i:7;C:10:"HelloWorld":4:{r:3;}i:8;C:10:"HelloWorld":4:{r:3;}} 

的問題是r:4;東西在第二次及以後的記錄。

回答

1

DAMN!對不起,我讀錯了你的問題。以爲你想打印所有的人。

您需要簡單才能序列化。否則它將無法正常工作,爲了序列化你需要使用類似這樣的東西:

class HelloWorld implements Serializable 
{ 
    public $test; 

    public function __construct($str) 
    { 
     $this->test = $str; 
    } 

    public function serialize() 
    { 
     return serialize($this->test); 
    } 

    public function unserialize($str) 
    { 
     $simple = unserialize($str); 
     $this->test = $simple; 
    } 
} 

簡單的類是不需要的。請記住$ this->數據總是必須是可序列化的。

+0

我的示例代碼是從原始案例進行簡化以更好地說明問題並從等式中刪除我們的一些支持庫。在我的原始代碼庫中,'HelloWorld'對應於一個模型類。 'Simple'對應於模板的通用數據類。我想要這樣的兩個類的原因是,在反序列化時,我可以重新創建數據庫連接。這是遺留代碼,所以我不能重新構建它。 –

+0

這很好。你只需要確保Simple類是可序列化的,你就可以隨意序列化和反序列化(不需要重建對象)。 您可以在反序列化時重新創建數據庫連接。這正是我在我的代碼中所做的。 –

相關問題