首页 > 解决方案 > 创建一个对象数组,然后在不丢失类的情况下获取对象

问题描述

我正在尝试对数组和对象进行一些实验,以提高我的 PHP 编程基础。

我想做的是将由我的一个类实例化的对象集合保存在一个文本文件中,以便以后能够获取它们。

我当前的实现是将对象保存在数组中,对数组进行编码并将其保存到 JSON 文件中。但是,出现的问题是,当我然后去提取对象时,这些对象不再是从我的类派生的对象,而是被转换为 stdClass 对象。

这是我用来将对象保存到文件的方法:

public function store(string $titolo, string $nomeAutore, string $titoloToDoList): void
    {
        FileChecker::FindOrBuild('Data/Tasks.json', "[]");

        $newTask = new Task($titolo, $nomeAutore, $titoloToDoList);
        $file = file_get_contents('Data/Tasks.json');
        $decodedFile = json_decode($file);
        array_push($decodedFile, $newTask->toArray());
        file_put_contents('Data/Tasks.json', json_encode($decodedFile));

        FileChecker::FindOrBuild('log/log.txt', "Logs: \n");
        Logger::logTaskStore($nomeAutore, $titoloToDoList);
    }

然后我用一个简单的 json_decode() 从文件中提取

谁能建议一些替代方法来将对象保存在文本文件中而不会丢失类?

编辑:忘记放toArray()简单的代码

public function toArray(): array
    {
        return get_object_vars($this);
    }

标签: phparraysjsonoop

解决方案


有多少人需要在文件中存储稍微不同的东西,就有多少文件格式。由您决定哪一个对您的应用程序有意义。

JSON 是一种文件格式,旨在非常简单和灵活,并且可以在许多不同的语言之间移植。它没有“类”或“自定义类型”的概念,它的“对象”类型只是键值对的列表。(查看您当前代码创建的文件,您会自己看到。)

You can build a file format "on top of" JSON: that is, rather than storing your objects directly, you first build a custom structure with a way of recording the class name, perhaps as a special key on each object called "__class". Then to decode, you first decode the JSON, then loop through creating objects based on the name you recorded.

You mentioned in comments PHP's built-in serialize method. That can be a good choice when you want to store full PHP data for internal use within a program, and will happily store your array of objects without extra code.

In both cases, be aware of the security implications if anyone can edit the serialized data and specify names of classes you don't want them to create. The unserialize function has an option to list the expected class names, to avoid this, but may have other security problems because of its flexibility.


推荐阅读