PHP how to json_encode object with private attribute

When using PHP’s json_encode function to encode an object that has private properties, you may encounter an error because json_encode cannot directly access private properties.

To work around this issue, you can define a method in your object that returns an array of the object’s properties, including the private ones. You can then call this method in your code when encoding the object.

Here’s an example:

class Person {
    private $name;
    private $age;

    public function __construct($name, $age) {
        $this->name = $name;
        $this->age = $age;

    public function toJson() {
        return [
            'name' => $this->name,
            'age' => $this->age

$person = new Person('John', 30);

echo json_encode($person->toJson());

In this example, the Person class has private properties $name and $age. The toJson method returns an array with the object’s properties, including the private ones.

To encode the Person object as JSON, we call the toJson method and pass its return value to json_encode.

The output will be a JSON string representing the object: