自动载入的类和上文工厂一样 这里是工厂+单例
单例 防止一次执行实例化多次同一个类 造成资源浪费。
实现方法:在被实例化的类 若果属性不存在 写一个静态方法实例化自己,保存到对象属性中。存在直接返回。
最好写个私有构造函数,防止不注意的时候被外部实例化。
index.php
<?php
define('BASEDIR',__DIR__);
include BASEDIR.'/Core/Loader.php';
spl_autoload_register('\\Core\\Loader::autoload');
$db=Core\Factory::createDatabases();
$db->conn();
?>
Databases.php
<?php
namespace Core;
class Database{
protected static $db;
private function __construct(){
}
public static function getInstance(){
if(self::$db){
return self::$db;
}else{
self::$db=new self();
return self::$db;
}
}
public function conn(){
echo "this is a method of connect database;";
}
}
?>
<?php
namespace Core;
class Factory{
public static function createDatabases(){
$db=Database::getInstance();
return $db;
}
}