从
http://www.php.net/manual/en/class.pdo.php
@H_403_16@
单例是一种软件设计模式,它将类的启动限制为一个实例.
http://en.wikipedia.org/wiki/Singleton_pattern
###### config.ini ###### db_driver=MysqL db_user=root db_password=924892xp [dsn] host=localhost port=3306 dbname=localhost [db_options] PDO::MysqL_ATTR_INIT_COMMAND=set names utf8 [db_attributes] ATTR_ERRMODE=ERRMODE_EXCEPTION ############ <?PHP class Database { private static $link = null ; private static function getLink ( ) { if ( self :: $link ) { return self :: $link ; } $ini = _BASE_DIR . "config.ini" ; $parse = parse_ini_file ( $ini,true ) ; $driver = $parse [ "db_driver" ] ; $dsn = "${driver}:" ; $user = $parse [ "db_user" ] ; $password = $parse [ "db_password" ] ; $options = $parse [ "db_options" ] ; $attributes = $parse [ "db_attributes" ] ; foreach ( $parse [ "dsn" ] as $k => $v ) { $dsn .= "${k}=${v};" ; } self :: $link = new PDO ( $dsn,$user,$password,$options ) ; foreach ( $attributes as $k => $v ) { self :: $link -> setAttribute ( constant ( "PDO::{$k}" ),constant ( "PDO::{$v}" ) ) ; } return self :: $link ; } public static function __callStatic ( $name,$args ) { $callback = array ( self :: getLink ( ),$name ) ; return call_user_func_array ( $callback,$args ) ; } } ?> <?PHP // examples $stmt = Database :: prepare ( "SELECT 'something' ;" ) ; $stmt -> execute ( ) ; var_dump ( $stmt -> fetchAll ( ) ) ; $stmt -> closeCursor ( ) ; ?>
我的问题是:
什么是单身人士?
静态意味着什么?
什么是公共静态函数__callStatic(用于?
静态意味着某些东西属于该类而不是特定实例.在PHP中,这也意味着需要使用:: not – >来调用静态方法.
_callStatic返回PDO链接(如果已经建立).否则,它首先创建链接然后返回它.
你的第四个问题的答案恰恰是单身人士模式.它确保仅在需要时才建立连接一次.