Skip to content

Core\Serialize

Turns a value into bytes and back. encode() writes the bytes, and decode() builds the same value again from them. Use it to save a value in a file or a cache and read it later.

Core\Serialize::encode copies the whole value graph under a value into bytes in Novis's own closed format, and decode rebuilds it: an object comes back as an instance of the class this program declares, its declared properties assigned directly — no constructor runs, and no hook method runs either. A cycle is preserved as a cycle. decode answers mixed, so narrow it with as; it refuses foreign bytes, another format version, and a class whose declared properties no longer match with ParseError, and encode throws LogicError on a callable. decode does not read bytes that name a generator, a function value or an open resource, such as a file. It throws a ParseError for them.

<?nvs
class Slot
{
public function constructor(public int $n)
{}
}
class Ring
{
public int $id = 0;
public ?Ring $self;
public function constructor(int $id)
{
$this->id = $id;
$this->self = null;
}
}
bytes $blob = Core\Serialize::encode(new Slot(7));
Slot $back = Core\Serialize::decode($blob) as Slot;
echo 'n=', $back->n, "\n";
var $ring = new Ring(1);
$ring->self = $ring;
Ring $copy = Core\Serialize::decode(Core\Serialize::encode($ring)) as Ring;
echo 'cycle=', ($copy->self?->id ?? 0), "\n";
try {
Core\Serialize::decode("O:4:\"Slot\":1:{s:1:\"n\";i:7;}" as bytes);
} catch (ParseError $e) {
echo "refused\n";
}
Output
n=7
cycle=1
refused

Members

2 members.

MemberSignature
encodeencode(mixed $value): bytes
decodedecode(bytes $payload): mixed