Deserializing from JSON into PHP, with casting?

前端 未结 12 2027
既然无缘
既然无缘 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:02

    I think the best way to handle this would be via the constructor, either directly or via a factory:

    class User
    {
       public $username;
       public $nestedObj; //another class that has a constructor for handling json
       ...
    
       // This could be make private if the factories below are used exclusively
       // and then make more sane constructors like:
       //     __construct($username, $password)
       public function __construct($mixed)
       {
           if (is_object($mixed)) {
               if (isset($mixed->username))
                   $this->username = $mixed->username;
               if (isset($mixed->nestedObj) && is_object($mixed->nestedObj))
                   $this->nestedObj = new NestedObject($mixed->nestedObj);
               ...
           } else if (is_array($mixed)) {
               if (isset($mixed['username']))
                   $this->username = $mixed['username'];
               if (isset($mixed['nestedObj']) && is_array($mixed['nestedObj']))
                   $this->nestedObj = new NestedObj($mixed['nestedObj']);
               ...
           }
       }
       ...
    
       public static fromJSON_by_obj($json)
       {
           return new self(json_decode($json));
       }
    
       public static fromJSON_by_ary($json)
       {
           return new self(json_decode($json, TRUE)); 
       }
    }
    

提交回复
热议问题