4,251
社区成员
![](https://csdnimg.cn/release/cmsfe/public/img/topic.427195d5.png)
![](https://csdnimg.cn/release/cmsfe/public/img/me.40a70ab0.png)
![](https://csdnimg.cn/release/cmsfe/public/img/task.87b52881.png)
![](https://csdnimg.cn/release/cmsfe/public/img/share-circle.3e0b7822.png)
class CI_Base {
public $start = 1;
private static $instance;
public function CI_Base()
{
self::$instance =& $this;
}
public static function &get_instance()
{
return self::$instance;
}
}
function &get_instance()
{
return CI_Base::get_instance();
}
$N = new CI_Base();
$A = &get_instance();
var_dump($A);
单例模式
class Example
{
// 保存类实例在此属性中
private static $instance;
// 构造方法声明为private,防止直接创建对象
private function __construct()
{
echo 'I am constructed';
}
// singleton 方法
public static function singleton()
{
if (!isset(self::$instance)) {
$c = __CLASS__;
self::$instance = new $c;
}
return self::$instance;
}
// Example类中的普通方法
public function bark()
{
echo 'Woof!';
}
// 阻止用户复制对象实例
public function __clone()
{
trigger_error('Clone is not allowed.', E_USER_ERROR);
}
}
这样我们可以得到一个独一无二的Example类的对象。
// 这个写法会出错,因为构造方法被声明为private
$test = new Example;
// 下面将得到Example类的单例对象
$test = Example::singleton();
$test->bark();
// 复制对象将导致一个E_USER_ERROR.
$test_clone = clone $test;
class ck{
public static function mycount(){
static $i;
$i=$i+1;
return $i;
}
}
echo ck::mycount();
echo ck::mycount();
echo ck::mycount();
echo ck::mycount();
//结果还是1234
function mycount(){
static $i;
$i=$i+1;
return $i;
}
echo mycount();
echo mycount();
echo mycount();
echo mycount();
function log_message($level = 'error', $message, $php_error = FALSE)
{
static $LOG; //看看这个,声明这个静态变量有何用?
$config =& get_config();
if ($config['log_threshold'] == 0)
{
return;
}
$LOG =& load_class('Log');
$LOG->write_log($level, $message, $php_error);
}
public function CI_Base()
{
self::$instance =& $this; //这个也很奇怪,引用了自身,而只有实例中才有$this,且不报错,难以理解
}
echo "<pre/>";
$N = new CI_Base();
unset($N);//摧毁
$A = &get_instance();//这就是函盖类吧?
echo $A->start;
echo "\n";
var_dump($A);