四私一公

 

<?php

namespace traits;

trait Singleton
{
    static private $instance;

    static public function getInstance()
    {
        if (is_null(static::$instance)) {
            $class = new \ReflectionClass(get_called_class());
            static::$instance = $class->newInstanceWithoutConstructor();
            $constructor = $class->getConstructor();
            $constructor->setAccessible(true);
            $default = [];
            foreach ($constructor->getParameters() as $parameter) {
                $default[] = $parameter->getDefaultValue();
            }
            $constructor->invokeArgs(static::$instance, array_replace_recursive($default, func_get_args()));
        }
        
        return static::$instance;
    }

    private function __construct()
    {
    }

    private function __clone()
    {
    }

    private function __wakeup()
    {
    }
}

 

相关文章:

  • 2021-07-09
  • 2021-06-21
  • 2022-12-23
  • 2022-01-18
  • 2021-07-09
  • 2021-09-25
  • 2021-11-25
猜你喜欢
  • 2021-06-08
  • 2022-12-23
  • 2021-07-11
  • 2021-09-28
  • 2021-05-24
  • 2022-03-09
相关资源
相似解决方案