Marc HPunkt
Marc HPunkt

Reputation: 439

How to ignore specific values when applying json_encode to class

Is there a way to ignore specific class attributes of a class in php when encoding to json.

For example in java with the jackson library I can annotate globals with @JsonIgnore to achieve this. Is there anything comparable (preferably native) in php??

Upvotes: 5

Views: 4163

Answers (1)

gen_Eric
gen_Eric

Reputation: 227240

One method is to utilize the JsonSerializable interface. This lets you create a function that's called when json_encode() is called on your class.

For example:

class MyClass implements JsonSerializable{
    public $var1, $var2;

    function __construct($a1, $a2){
        $this->var1 = $a1;
        $this->var2 = $a2;
    }

    // From JsonSerializable
    public function jsonSerialize(){
        return ['var1' => $this->var1];
    }
}

So, when json_encode() is called, only var1 will be encoded.

$myObj = new MyClass(10, 20);
echo json_encode($myObj); // {"var1":10}

DEMO: https://eval.in/103959

Note: This only works on PHP 5.4+

Upvotes: 8

Related Questions