single-mode embodiment php

Normal singleton pattern directly in a class are directly implemented by a public private three ways, of course, this is one of the most common implementation, of course, there are other ways.

In easyswoolethe by implementing a traitget way singleton object, I think there is some reference, excerpted here, as the notes.

Singleton.php

<?php
/**
 * Created by PhpStorm.
 * User: yf
 * Date: 2018/5/24
 * Time: 下午3:56
 */
// 这里的命名空间要根据实际情况修改一下即可。
namespace EasySwoole\Component;

trait Singleton
{
    private static $instance;

    static function getInstance(...$args)
    {
        if(!isset(self::$instance)){
            self::$instance = new static(...$args);
        }
        return self::$instance;
    }
}

Want to achieve in a single class of embodiments, as long as use useis introduced to. example:

<?php

use EasySwoole\Component\Singleton;

class Test
{
	// 在这里通过 use 引入 trait
	use Singleton;
	
	public function test()
	{
	}
}
Published 48 original articles · won praise 13 · views 10000 +

Guess you like

Origin blog.csdn.net/weixin_37825371/article/details/104200326