PHP code example of yashuk803 / serializer

1. Go to this page and download the library: Download yashuk803/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/ */

    

yashuk803 / serializer example snippets




class Person
{
    const MAX_POSSIBLE_AGE = 150;
    private $firstName;
    private $lastName;
    private $age;
    public function __construct($firstName, $lastName)
    {
        $this->firstName = $firstName;
        $this->lastName = $lastName;
    }
    public function __get($name)
    {
        $getter = 'get' . \ucfirst($name);
        if (\method_exists($this, $getter)) {
            return $this->$getter();
        }
    }
    public function getFirstName()
    {
        return $this->firstName;
    }
    public function getLastName()
    {
        return $this->lastName;
    }
    public function setAge($age)
    {
        if ($age > self::MAX_POSSIBLE_AGE) {
            throw new InvalidAgeOfPersonException($age);
        }
        $this->age = $age;
    }
    public function getAge()
    {
        return $this->age;
    }
    public function __toString()
    {
        return $this->firstName . ' ' . $this->lastName;
    }
}

#!/usr/bin/env php


\Test\Person;
use Yashuk803\Serializer\Serializer;
use Yashuk803\Serializer\Encoder\JsonEncoder;
use Yashuk803\Serializer\Encoder\YamlEncoder;

$person = new Person('Marina', 'Bulick');
$person->setAge(30);



$serialized = new Serializer($person, new YamlEncoder());
$serialized->serialize();
/*
firstName: Marina
lastName: Bulick
age: 30
*/

$serialized = new Serializer($person, new JsonEncoder());
$serialized->serialize();
/*{"firstName":"Marina","lastName":"Bulick","age":30}*/