Deserializing from JSON into PHP, with casting?

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

    Maybe the hydration pattern can be of help.

    Basically you instantiate an new empty object (new User()) and then you fill in the properties with values from the StdClass object. For example you could have a hydrate method in User.

    If possible in your case, you can make the User constructor accept an optional parameter of type StdClass and take the values at instantiation.

提交回复
热议问题