Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/246.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP数组序列化,其中值实现可序列化_Php_Arrays_Class_Serialization_Interface - Fatal编程技术网

PHP数组序列化,其中值实现可序列化

PHP数组序列化,其中值实现可序列化,php,arrays,class,serialization,interface,Php,Arrays,Class,Serialization,Interface,我遇到了一个奇怪的问题,如果我尝试序列化同一类的对象数组,该类实现了Serializable接口,在Serializable接口中返回另一个类的序列化实例,则前两个类之后的数组项被认为是递归的 下面是一个测试用例: <?php class HelloWorld implements Serializable { public $test; public function __construct($str) { $this->test = $

我遇到了一个奇怪的问题,如果我尝试序列化同一类的对象数组,该类实现了Serializable接口,在Serializable接口中返回另一个类的序列化实例,则前两个类之后的数组项被认为是递归的

下面是一个测试用例:

<?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));

问题是
r:4第二条和后面的记录上的内容。

该死!对不起,我看错了你的问题。我以为你想把它们都印出来

您需要简单才能序列化。否则它将无法工作,为了序列化,您需要使用以下内容:

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->数据始终必须是可序列化的。

我的示例代码从原始案例中进行了简化,以更好地说明这个问题,并从公式中删除一些支持库。在我的原始代码库中,
HelloWorld
对应于一个模型类<代码>简单
对应于模板的通用仅数据类。我想要这两个类的原因是,在取消序列化时,我可以重新创建数据库连接。这是遗留代码,所以我不能重新构建它。它非常好。您只需确保简单类是可序列化的,并且可以随意序列化和取消序列化(无需重建对象)。您可以在取消序列化时重新创建数据库连接。这正是我在代码中所做的。
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;
    }
}