<?php

/*

场景:

class mysql {

}



$my1 = new mysql();

$my2 = new mysql();

$my3 = new mysql();


每new一次,连接一次数据库

同时,多了一个对象,增大的开销



另一种场景:购物车

如果我打开多个页面,每个页面实例了多个购物车

那么下的订单,可能会被装在不同的购物车里,出现错误.

所以,购物车,也得保证,只有有一个实例.



问:如何保证让大家使的$my1,$my2,$my3,是同一个对象?

*/


//类的静态属性

//类的静态属性和其他属性不一样

/*

class human{

static public $leg=2;

public $name;

public function __construct($name){

$this->name=$name;

}

public function showlegs(){

echo self::$leg;

}

}

$zhangsan=new human('张三');

$lisi=new human('李四');

print_r($zhangsan);// 多个对象,就有多个name普通属性.

print_r($lisi);

$lisi->showlegs();

*/

/*

class human{

static public $leg=2; // 这个数字2不属于张三,不属于李四,而属于全人类

static public function ins(){

echo 'aaa';

echo self::$leg;

//echo $this->name;// Using $this when not in object context self 是指类本身 $this是指对象本身

}

public $name;

public function _construct($name){

$this->name=$name;

}

public function showleg(){

echo self::$leg;

}

}

$zhangsan=new human('张三');

$lisi=new human('李四');

// 不创建任何实例/对象, 调用human的$leg静态属性

human::ins();

/*

1:静态属性/方法,属于全类,而不属于对象.

2:在内存中,只有一份.

3:调用静态属性/方法,用类名::$属性名,类名::方法名()来调用, 不依赖对象

*/

//单例模式第0步

/*

class mysql{

public $rand;

public function __construct(){

$this->rand=rand(10000,99999);

}

}

$m1=new mysql();

$m2=new mysql();

print_r($m1);

print_r($m2);

*/

//单例模式第一步不允许进行new操作

/*

class mysql{

public $rand;

protected function __construct($rand){

$this->rand=$rand;

}

}

$m1=new mysql;

*/

//在类中开放一个借口进行实例化对象

/*

class mysql{

public $rand;

static function ins(){

return new mysql;

}

protected function __construct(){

$this->rand=rand(1000,9999);

}

}

$m1=mysql::ins();

$m2=mysql::ins();

print_r($m1);

print_r($m2);

*/

// 单例模式第3步,加判断,判断该类的实例是否已经存在.

class mysql{

public $rand;

static public $flag=null;

static function ins(){

if(self::$flag){

self::$flag=new mysql;

return self::$flag;

}

return self::$flag;

}

 final protected function __construct(){

$this->rand=rand(1000,9999);

}

}

$m1=mysql::ins();

$m2=mysql::ins();


class my extends mysql{

public $name;

}

//$m1=new my();不能被new了

//$m2=new my();不能被new了

print_r($m1);

print_r($m2);

if($m1===$m2){

echo '是同一个对象';

}

else{

echo "不是一个对象";

}

// 问题:子类继承时,允许同名方法覆盖父类的同名方法,且权限越来越宽松.

// 某个方法,继承可以,但是不允许重写.

// final,关键字.可以修饰类名  方法名 修饰类名的时候不能继承 修饰方法的时候不能重写

//还有可能通过克隆得倒两个对象


?>