データベース(MySQLi)に接続しようとしましたが、問題が発生しています。グローバル変数 - データベース接続?
スクリプト全体に対してグローバルに接続するにはどうすればよいですか?複数のファイル(index.php、/classes/config.class.php、/classes/admin.class.phpなど)があります。
私は次のことを試してみた:で
:config.class.php
public static $config = array();
public static $sql;
function __construct() {
// database
db::$config['host'] = 'localhost';
db::$config['user'] = '_';
db::$config['pass'] = '_';
db::$config['db'] = '_';
// connect
db::$sql = new mysqli(db::$config['host'], db::$config['user'], db::$config['pass'], db::$config['db']);
}
ここでも、config.class.php
public function contectToDatabase($sql){
$sql = new mysqli(db::$config['host'], db::$config['user'], db::$config['pass'], db::$config['db']);
$this->sql = $sql;
}
に私はクラスを使用します次のコード: $config = new db();
私は本当に困惑していますどのように私はこれを行うにはt。誰も助けることができますか?
---編集--- これは私の新しいconfig.class.phpファイルです:
public static $config = array();
public static $sql;
private static $db;
private $connection;
public function __construct() {
// database
db::$config['host'] = '_';
db::$config['user'] = '_';
db::$config['pass'] = '_';
db::$config['db'] = '_';
// connect
$this->connection = new mysqli(db::$config['host'], db::$config['user'], db::$config['pass'], db::$config['db']);
}
function __destruct() {
$this->connection->close();
}
public static function getConnection() {
if($db == null){
$db = new db();
}
return $db->connection;
}
そして、これは私がそれをロードしています方法です。しかし、
require_once("classes/config.class.php");
$config = new db();
$sql = db::getConnection();
を実行していますreal_escape_stringの結果、次のエラーが発生します。
Warning: mysqli::real_escape_string() [mysqli.real-escape-string]: Couldn't fetch mysqli in /home/calico/_/_.com/_/index.php on line 20
Warning: mysqli::query() [mysqli.query]: Couldn't fetch mysqli in /home/calico/_/_.com/_/index.php on line 28
[シングルトンパターン](http://en.wikipedia.org/wiki/Singleton_pattern) – knittl
を使用することも、[シングルトン反パターン](http://stackoverflow.com/)を使用する代わりに依存性注入を学習することもできます。質問/ 4595964/who-needs-singletons/4596323#4596323) – Gordon
ええと...シングルトンは常に熱い議論につながります。私はちょうど入力とアイデアを与えていた – knittl