I think this is mostly because I'm new to PHP OOP, but I have a quick question that I can't seem to find an answer for. Since I use the same connection information for several methods, I tired to take out the information and put them into property variables as private and static. However, when trying to make a PDO connection, this doesn't work:
class MyClass {
private static $DSN = "mysql:host=localhost;dbname=testdb";
private static $USR = "user";
private static $PWD = "password";
public static function connection() {
$pdo = new PDO($DSN, $USR, $PWD);
//more code
}
}
Yet when I enter the information manually, it works fine:
class MyClass {
public static function connection() {
$pdo = new PDO("mysql:host=localhost;dbname=testdb", "user", "password");
//more code
}
}
So why doesn't using a set of properties work? I spent a few hours trying to get it to work and it just didn't, only to find out that that was the problem. I'm fine with manually connecting but I would like to know why the first solution doesn't work.
You need the self
keyword (along with the scope resolution operator ::
) to access those private static properties.
$pdo = new PDO( self::$DSN, self::$USR, self::$PWD);
Otherwise you're not referencing the correct variables.
See the manual for more information about static keywords.
You are calling your values incorrectly.
$pdo = new PDO( self::$DSN, self::$USR, self::$PWD);
Or
$pdo = new PDO( MyClass::$DSN, MyClass::$USR, MyClass::$PWD);