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 easyswoole
the by implementing a trait
get 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 use
is introduced to. example:
<?php
use EasySwoole\Component\Singleton;
class Test
{
// 在这里通过 use 引入 trait
use Singleton;
public function test()
{
}
}