json_encodewill return a JSON object with the public properties of the object passed to it. If you want to enable randomNumber, you can make it public and set it in the constructor, for example
class Example
{
public $id;
public $name;
public $randomNumber;
public function __construct() {
$this->randomNumber = $this->getRandomNumber();
}
public function getRandomNumber()
{
return rand();
}
}
For more complex serialization of objects, you can see the symfony serializer
source
share