range

If there were you, the world would be just right

单例模式的定义
确保某一个类只有一个实例,不能重复实例,只能它自己实例化,而且向整个系统提供这个实例。

在有trait之前,无法实现让父类实现单例模式,让子类去继承。trait的出现很自然地解决了这个问题,我们可以写一个实现单例的trait,然后把它组合到任何想实现单例的类

<?php

trait DlTrait {

    protected static $instance = null;

    public static function instance() {
        if (null === self::$instance) {
            self::$instance = new static();
        }
        return self::$instance;
    }
}

class a
{
    use DlTrait;
}

$a = a::instance();
$b = a::instance();

if($a === $b){
    echo "相同";
}else{
    echo "不相同";
}