PHP

PHP中使用Trait实现单例模式 | 深入理解PHP设计模式

silverwq
2022-10-18 / 1 评论 / 276 阅读 / 正在检测是否收录...
<?php

trait Singleton
{
    private static $instance;

    /**
     * @param mixed ...$args
     * @return static
     */
    static function getInstance(...$args)
    {
        if (!isset(static::$instance)) {
            static::$instance = new static(...$args);
        }
        return static::$instance;
    }
}

class Test
{
    use Singleton;

    public function __construct($a, $b, $c)
    {
        echo $a, $b, $c;
    }
}
Test::getInstance(1, 2, 3);
// 输出123
0

评论 (1)

取消
  1. 头像
    silverwq 作者
    Windows 10 · Google Chrome

    画图

    回复