0

I am trying out json_encode for the first time I created an object

class Test {
  public $action= 'sleep';

  public function wake() {
    $this->action = 'wake';
  }
}

then I encode it

$enc_obj = json_encode(new Test());

I then var_dump()ed it

var_dump($enc_obj);

I got a list of the property without the functions

'{"action":"sleep"}'

Am I missing something or that is how it is supposed to work?

Plamen Petrov
  • 4,669
  • 4
  • 30
  • 41
twist
  • 93
  • 8

1 Answers1

3

json_encode() will only output data in a JSON format. The JSON format does not support any functions, neither javascript nor PHP functions. As noted on http://www.json.org, it is a "lightweight data-interchange format." - not a programming language.

See also Is it valid to define functions in JSON results?

In PHP, you may extend the jsonSerializeable interface to manually define how the JSON result should be.

Community
  • 1
  • 1
Jan Sverre
  • 4,471
  • 1
  • 21
  • 26