-
-
Save tommcfarlin/e87e029f8e28ec9681996761f06d7347 to your computer and use it in GitHub Desktop.
[WordPress] Class Serialization with PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Acme implements JsonSerializable | |
{ | |
/** | |
* @var string the name of the model as represented on the front-end. | |
*/ | |
protected $name; | |
// More code here. | |
/** | |
* @return string a JSON representation of this class | |
*/ | |
public function jsonSerialize() | |
{ | |
return [ | |
'name' => $this->getName() | |
]; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Acme implements JsonSerializable | |
{ | |
/** | |
* @var string the name of the model as represented on the front-end. | |
*/ | |
protected $name; | |
/** | |
* @var array an array of features about this object. | |
*/ | |
protected $features; | |
// More code here. | |
/** | |
* @return string a JSON representation of this class | |
*/ | |
public function jsonSerialize() | |
{ | |
return [ | |
'name' => $this->getName(), | |
'features' => [ | |
'hair' => $this->getHairColor(), | |
'eyes' => $this->getEyeColor(), | |
], | |
]; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Acme implements JsonSerializable | |
{ | |
/** | |
* @var string the name of the model as represented on the front-end. | |
*/ | |
protected $name; | |
/** | |
* @var array an array of features about this object. | |
*/ | |
protected $features; | |
// More code here. | |
/** | |
* @return string a JSON representation of this class | |
*/ | |
public function jsonSerialize() | |
{ | |
$objectArray = []; | |
foreach ($this as $key => $value) { | |
$objectArray[$key] = $value; | |
} | |
return $objectArray; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment