PHP code example of gilsegura / serializer

1. Go to this page and download the library: Download gilsegura/serializer library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

gilsegura / serializer example snippets


use Serializer\SerializableInterface;

/**
 * @implements SerializableInterface<array{x: int, y: int}>
 */
final readonly class Point implements SerializableInterface
{
    public function __construct(
        public int $x,
        public int $y,
    ) {
    }

    public static function deserialize(array $attributes): static
    {
        return new self($attributes['x'], $attributes['y']);
    }

    public function serialize(): array
    {
        return ['x' => $this->x, 'y' => $this->y];
    }
}

/**
 * @implements SerializableInterface<array<int>>
 */
final readonly class NumberCollection implements SerializableInterface
{
    /** @var int[] */
    public array $numbers;

    public function __construct(int ...$numbers)
    {
        $this->numbers = $numbers;
    }

    public static function deserialize(array $attributes): static
    {
        return new self(...$attributes);
    }

    public function serialize(): array
    {
        return $this->numbers;
    }
}

use Serializer\Serializer;

$serialized = Serializer::serialize(new Point(1, 2));
// ['class' => Point::class, 'attributes' => ['x' => 1, 'y' => 2]]

$point = Serializer::deserialize($serialized);
// Point(1, 2)