I am trying to convert a simple class object to json as string. It does not work!. could you help me please.
here are my files:
Peson.php
<?php
class Person
{
private $name;
public function getName()
{
return $this->name;
}
public function setName($name)
{
$this->name = $name;
}
public function toJson()
{
return json_encode($this);
}
}
?>
index.php
include 'Person.php';
$person = new Person();
$person->setName("John");
echo $person->toJson();
Result :
CodePudding user response:
You're getting an empty object because your class doesn't have any public properties to encode. Change name
from private
to public
and you'll get output like this: {"name":"John"}
CodePudding user response:
You can use get_object_vars for this.
public function toJson()
{
return json_encode(get_object_vars($this)); //returns {"name":"stringNameHere"}
}
More info about get_object_vars here.
This is how your code would look:
class Person
{
private $name;
public function getName()
{
return $this->name;
}
public function setName($name)
{
$this->name = $name;
}
public function toJson()
{
return json_encode(get_object_vars($this));
}
}
$person = new Person();
$person->setName('testName');
echo $person->toJson(); //Print {"name":"testName"}
Here you have a live code example
CodePudding user response:
In this case you get an empty object because the properties are private. A way to keep your properties private and still geting their values in a JSON is using the JsonSerializable
Interface. Then implementing its method jsonSerialize()
.
class Person implements JsonSerializable
{
private $name;
public function getName()
{
return $this->name;
}
public function setName($name)
{
$this->name = $name;
}
public function jsonSerialize()
{
$vars = get_object_vars($this);
return $vars;
}
}
CodePudding user response:
<?php
class Person implements \JsonSerializable
{
private $name;
public function getName()
{
return $this->name;
}
public function setName($name)
{
$this->name = $name;
}
public function jsonSerialize()
{
return get_object_vars($this);
}
}
?>
then, you can convert your person object to JSON with json_encode
$person = new Person();
$person->setName("John");
echo json_encode($person);