Deserializing from JSON into PHP, with casting?

前端 未结 12 2042
既然无缘
既然无缘 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 04:47

    To answer your direct question, no, there's no was to do this with json_encode/json_decode. JSON was designed and specified to be a format for encoding information, and not for serializing objects. The PHP function don't go beyond that.

    If you're interested in recreating objects from JSON, one possible solution is a static method on all the objects in your hierarchy that accepts a stdClass/string and populates variables that looks something like this

    //semi pseudo code, not tested
    static public function createFromJson($json){
        //if you pass in a string, decode it to an object
        $json = is_string($json) ? json_decode($json) : $json;
    
        foreach($json as $key=>$value){
            $object = new self();
            if(is_object($value)){
                $object->{$key} = parent::createFromJson($json);
            }
            else{
                $object->{$key} = $value;
            }
        }
    
        return $object;
    }
    

    I didn't test that, but I hope it gets the idea across. Ideally, all your objects should extend from some base object (usually named "class Object") so you can add this code in one place only.

提交回复
热议问题