Created
April 16, 2019 19:24
-
-
Save stefpe/dc7d97d02984898cc97eb8e33be5e9a3 to your computer and use it in GitHub Desktop.
json serializable class
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 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