一:代码
1:单态类
<?php
namespace app\wechat\controller;
trait Instance
{
static private $instance;
/**
* 防止被外部new类
*/
private function __construct(){}
/**
* 防止被继承者克隆
*/
private function __clone(){}
static function getInstance()
{
if ( !isset( self::$instance ) ) {
self::$instance = new static();
}
return self::$instance;
}
}
2:继承单态的类
<?php
namespace app\wechat\controller;
class Test
{
use Instance;
private $config;
function set( $index, $value )
{
$this->config[ $index ] = $value;
}
function get( $index )
{
var_dump($this->config[ $index ]);
}
}
二:执行方式
$model = Test::getInstance();
$model->set( "index", "设置index参数值" );
$models = Test::getInstance();
$models->get( "index" );
三:执行结果
string(20) "设置index参数值"
说明:$models 获取的Test对象实例, 是$model,单态实现成功