1

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.

1
  • Did you check to see if you were getting any errors back from the database? Commented Jun 21, 2012 at 18:35

2 Answers 2

3

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.

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

4 Comments

hah What a stupid mistake to make. Again I'm new to the PHP OOP. I guess I need to learn when to use things like self and this (tried $this as well but that didn't work). Thank you.
You're welcome! It's a common mistake and a part of the learning process. :)
So for future reference, if I need to access those variables anywhere for any reason (inside the class), I'll always have to refer to them as 'self::$var'?
If they are static. If they're not, you'll use $this->DSN, etc.
1

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); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.