したがって、この問題には2つのファイルが関係しています。それらの 1 つは Database クラスであり、もう 1 つはinclude_once
Database ファイルであり、そのクラスのオブジェクトをインスタンス化して関数を呼び出すファイル -- getDB(); です。それが間違っているところです。
データベース クラス:
<?php
class Database {
private static $datasource='mysql:host=localhost; dbname=db_name';
private static $username='root';
private static $password='root';
private static $db;
private function __construct(){}
public static function getDB(){
if(!isset(self::$db)){
try{
self::$db=new PDO(self::$datasource,self::$username,self::$password);
}
catch(PDOExceptin $e) {
$error=$e->getMessage(); //variable $error can be used in the database_error.php file
//display database error file.
//include('database_error.php');
exit();
}
}
return self::$db;
}
function Database(){
return new Database;
}
}
?>
そして、私のメインファイルで、私はこれをやっています:
<?php
include('partials/header.php');
include_once('functions/pdo.php');
$database = new Database();
$getdb = $database->getDB();
//Anything below won't show because of the failed instantiation of Database object above.
//code..
?>
明らかに、私はここで何か間違ったことをしています。PHP 5.3でMAMPを実行しています。データベースを正しく使用するにはどうすればよいですか? クラスと同じ名前の関数がある理由は、代わりに関数を使用してオブジェクトをインスタンス化できると読んだためですが、それも機能しませんでした...