Ben driftig bezig om mijn PhP bij te spijkeren op OOP gebied. Nu probeer ik dmv het singleton concept 1 database instance te maken. Het lijkt er op dat ik prima een instance kan aanmaken van de DatabaseConnection. Het probleem doet zich voor als ik vanuit deze instance een methode wil aanroepen (in dit geval query). Als ik index.php aan roep, dan laad hij prima "Constructor called" zien, echter
niet "Running query on database connection...". Iemand enig idee hoe dit kan?
PHP: index.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
| <?php
require_once 'DatabaseConnection.class.php';
class index {
public function __construct() {
$dbInstance = DatabaseConnection::getInstance();
$dbInstance->query;
}
}
new index();
?> |
PHP: DatabaseConnection.class.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
| <?php
class DatabaseConnection
{
// Store the single instance of Database
private static $m_pInstance;
// Private constructor to limit object instantiation to within the class
private function __construct()
{
echo "Constructor called<br />\n";
}
// Getter method for creating/returning the single instance of this class
public static function getInstance()
{
if (!self::$m_pInstance)
{
self::$m_pInstance = new DatabaseConnection();
}
return self::$m_pInstance;
}
// Test function to simulate a query
public function query()
{
echo "Running query on database conenction...<br />\n";
}
} ?> |