I’m trying my hand at OO PHP however when I try the code I get errors saying that dbhost, dbuser,dbpass and dbname are undefined. Netbeans also gives me a warning saying that they might be uninitialized.
Removing the static keyword gives me an error saying ‘Unexpected “$dbhost” ‘.
Does anyone know what I’m doing wrong?
<?php
class DatabaseManager {
private static $dbhost = 'localhost';
private static $dbuser = 'root';
private static $dbpass = '';
private static $dbname = 'app_db';
public static function getConnection(){
$dbconn;
try {
$dbconn = new PDO('mysql:host='.$dbhost,'dbname='.$dbname,
$dbuser, $dbpass);
} catch (PDOException $e) {
echo "Could not connect to database";
echo $e;
exit;
}
return $dbconn;
}
}
?>
You’ve declared your variable static. Reference them like this in php 5.2 or higher:
In PHP 5.3 or higher if you set them from private to protected you can also use:
They both act similarly, but if you extend the class, the static keyword allows for late static binding.