Jack Hurt
Jack Hurt

Reputation: 80

OO PHP undefined variables

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;

}

}
?>

Upvotes: 2

Views: 985

Answers (1)

Ray
Ray

Reputation: 41428

You've declared your variable static. Reference them like this in php 5.2 or higher:

$dbconn = new PDO('mysql:host='.self::$dbhost,'dbname='.self::$dbname,
                   self::$dbuser, self::$dbpass);   

In PHP 5.3 or higher if you set them from private to protected you can also use:

$dbconn = new PDO('mysql:host='.static::$dbhost,'dbname='.static::$dbname,
                   static::$dbuser, static::$dbpass);   

They both act similarly, but if you extend the class, the static keyword allows for late static binding.

Upvotes: 3

Related Questions