<?php


namespace Mnv\Core\Singleton;

/**
 * Trait SingletonTrait
 * @package Mnv\Core\SingletonTrait
 */
trait SingletonTrait
{

    /**
     * @return self
     */
    public static function init(): self
    {
        static $instances;

        $calledClass = get_called_class();

        if (!isset($instances[$calledClass])) {
            $instances[$calledClass] = new $calledClass();
        }

        return $instances[$calledClass];
    }


    /**
     * @throws SingletonException
     */
    public function __clone()
    {
        throw new SingletonException('You can not clone a singleton.');
    }

    /**
     * @throws SingletonException
     */
    public function __sleep()
    {
        throw new SingletonException('You can not serialize a singleton.');
    }

    /**
     * @throws SingletonException
     */
    public function __wakeup()
    {
        throw new SingletonException('You can not deserialize a singleton.');
    }

}