2

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;

}

}
?>
1
  • Unrelated to the problem: You don't have to declare variables in PHP, so there is no point in doing $dbconn; at the beginning of your method (this just has no effect at all). Commented Aug 11, 2012 at 14:26

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Since the member variables are declared private, I wouldn't recommend using static. That may otherwise lead to some problems with subclasses.
@Niko see my comment above the static example, it indicates he should switch from private to protected to use static.
Another quick question, does PHP handle the scope of variables differently than java? In my code above $dbconn; is unused and I can return the dbconn variable that is initialized inside the try
@JackHurt mostly it's the same. Since php doesn't have packages it's simpler using the protected keyword. You can declare $dbconn to be a static protected property as well outside of the method and use it without having to return it.
@JackHurt Yes, there is a difference. Java has a block scope, so that a variable is only defined inside the closest pair of curly brackets. In PHP it's a function scope, meaning that a variable is always defined in the whole function (as you may have already guessed from the name ^^).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.