Deserializing from JSON into PHP, with casting?

前端 未结 12 2023
既然无缘
既然无缘 2021-01-31 04:38

Suppose I have a User class with \'name\' and \'password\' properties, and a \'save\' method. When serializing an object of this class to JSON via json_encode, the method is pro

12条回答
  •  别那么骄傲
    2021-01-31 05:08

    I'm aware that JSON doesn't support the serialization of functions, which is perfectly acceptable, and even desired. My classes are currently used as value objects in communicating with JavaScript, and functions would hold no meaning (and the regular serialization functions aren't usable).

    However, as the functionality pertaining to these classes increases, encapsulating their utility functions (such as a User's save() in this case) inside the actual class makes sense to me. This does mean they're no longer strictly value objects though, and that's where I run into my aforementioned problem.

    An idea I had would have the class name specified inside the JSON string, and would probably end up like this:

    $string = '{"name": "testUser", "password": "testPassword", "class": "User"}';
    $object = json_decode ($string);
    $user = ($user->class) $object;
    

    And the reverse would be setting the class property during/after json_encode. I know, a bit convoluted, but I'm just trying to keep related code together. I'll probably end up taking my utility functions out of the classes again; the modified constructor approach seems a bit opaque and runs into trouble with nested objects.

    I do appreciate this and any future feedback, however.

提交回复
热议问题