Deserializing from JSON into PHP, with casting?

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

    Short answer: No (not that I know of*)

    Long answer: json_encode will only serialize public variables. As you can see per the JSON spec, there is no "function" datatype. These are both reasons why your methods aren't serialized into your JSON object.

    Ryan Graham is right - the only way to re-create these objects as non-stdClass instances is to re-create them post-deserialization.

    Example

    firstName = $firstName;
            $this->lastName = $lastName;
        }
    
        public static function createFromJson( $jsonString )
        {
            $object = json_decode( $jsonString );
            return new self( $object->firstName, $object->lastName );
        }
    
        public function getName()
        {
            return $this->firstName . ' ' . $this->lastName;
        }
    }
    
    $p = new Person( 'Peter', 'Bailey' );
    $jsonPerson = json_encode( $p );
    
    $reconstructedPerson = Person::createFromJson( $jsonPerson );
    
    echo $reconstructedPerson->getName();
    

    Alternatively, unless you really need the data as JSON, you can just use normal serialization and leverage the __sleep() and __wakeup() hooks to achieve additional customization.

    * In a previous question of my own it was suggested that you could implement some of the SPL interfaces to customize the input/output of json_encode() but my tests revealed those to be wild goose chases.

提交回复
热议问题