Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
[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