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 G
  • 4,729
  • 4
  • 33
  • 44
twist
  • 103
  • 8
  • 1
    Yes you are missing the fact that when you serialize an object only the data is serialized, not the code. How is it supposed to serialize something you are supposed to "execute"? – Johnny Oct 16 '16 at 16:19
  • thank you very much, i didn't think to that direction. – twist Oct 16 '16 at 16:28
  • added relevant tag, fixed grammar, added code formatting – Plamen G Oct 19 '16 at 07:12

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,617
  • 1
  • 22
  • 28