Skip to content

Instantly share code, notes, and snippets.

@tommcfarlin
Created February 26, 2019 15:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tommcfarlin/e87e029f8e28ec9681996761f06d7347 to your computer and use it in GitHub Desktop.
Save tommcfarlin/e87e029f8e28ec9681996761f06d7347 to your computer and use it in GitHub Desktop.
[WordPress] Class Serialization with PHP
<?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()
];
}
}
<?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(),
],
];
}
}
<?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