How to convert object to JSON in PHP

1 Answer

0 votes
class Person
{
    public $name;
    public $age;
    public $like;
 
    public function __construct(array $data) {
        $this->name = $data['name'];
        $this->age = $data['age'];
        $this->like = $data['like'];
    }
}
 
$obj = new Person(array('name' => 'Tom', 'age' => 46, 'like' => 'JavaScript'));
 
$JSON = json_encode($obj);

print_r($obj);
 
echo $JSON;
 
 
 
 
 
/*
run:
 
Person Object
(
    [name] => Tom
    [age] => 46
    [like] => JavaScript
)
{"name":"Tom","age":46,"like":"JavaScript"}
 
*/

 



answered Feb 15, 2021 by avibootz
edited Feb 15, 2021 by avibootz

Related questions

1 answer 203 views
203 views asked Sep 20, 2021 by avibootz
1 answer 221 views
221 views asked Sep 20, 2021 by avibootz
1 answer 242 views
1 answer 304 views
1 answer 241 views
241 views asked May 24, 2022 by avibootz
1 answer 250 views
...