L'interfaccia JsonSerializable è costituita da un unico metodo astratto jsonSerialize()
Codice PHP
JsonSerializable {
abstract public jsonSerialize() : mixed
}
pertanto per implementare questa interfaccia in una classe bisogna integrare la funzione jsonSerialize(), ad esempio
Codice PHP
<?php
class UserDev implements JsonSerializable
{
public $github;
public $npmjs;
public $codepen;
public function __construct(string $github, string $npmjs, string $codepen)
{
$this->github = $github;
$this->npmjs = $npmjs;
$this->codepen = $codepen;
}
public function jsonSerialize()
{
return ["github" => $this->github, "npmjs" => $this->npmjs, "codepen" => $this->codepen, ];
}
}
echo json_encode(new UserDev('MicheleDef', '~micheledef', 'MicheleDef') , JSON_PRETTY_PRINT);
grazie all'utilizzo dell'opzione JSON_PRETTY_PRINT l'output di questo esempio è un file json
{
"github": "MicheleDef",
"npmjs": "~micheledef",
"codepen": "MicheleDef"
}
nello specifico il risultato del metodo jsonSerialize() viene utilizzato come parametro di ingresso della funzione json_encode().