Skip to content

Instantly share code, notes, and snippets.

@stefpe
Created April 16, 2019 19:24
Show Gist options
  • Save stefpe/dc7d97d02984898cc97eb8e33be5e9a3 to your computer and use it in GitHub Desktop.
Save stefpe/dc7d97d02984898cc97eb8e33be5e9a3 to your computer and use it in GitHub Desktop.
json serializable class
<?php
/**
* Class Person
*/
class Person implements JsonSerializable
{
/**
* @var string
*/
private $firstname;
/**
* @var string
*/
private $lastname;
/**
* @return string
*/
public function getFirstname(): string
{
return $this->firstname;
}
/**
* @param string $firstname
* @return Person
*/
public function setFirstname(string $firstname): Person
{
$this->firstname = $firstname;
return $this;
}
/**
* @return string
*/
public function getLastname(): string
{
return $this->lastname;
}
/**
* @param string $lastname
* @return Person
*/
public function setLastname(string $lastname): Person
{
$this->lastname = $lastname;
return $this;
}
/**
* @return array|mixed
*/
public function jsonSerialize()
{
return [
'person' => [
'firstname' => $this->firstname,
'lastname' => $this->lastname
]
];
}
}
$person = new Person();
$person
->setFirstname('Jeff')
->setLastname('Johnson');
echo json_encode($person);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment