gthuo
gthuo

Reputation: 2566

Scope of PDO variables

This might be fairly simple but I don't know how. Now, I'm using PDO to access MySQL. I create a connection to the db at the top of the script e.g. $db=new PDO("mysql:host=localhost; dbname=xyz",'usnm','pswd') Now when I call a function, it says that the variable $db is undefined. I have put the function in an external script which I have required at the top of the script. Now my question is, what is the scope of PDO variables? Does it extend to functions called inside the script?

Upvotes: 0

Views: 146

Answers (1)

Prisoner
Prisoner

Reputation: 27618

This isn't to do with the scope of "PDO variables", it's just variables in general. In PHP, you can't access any variable throughout the whole application without a little bit of extra work. Refer to the variable scope documentation.

You can inject the database variable like:

function something($db){
}

and then pass the database variable into the function, or you could do:

function something(){
  global $db;
}

Upvotes: 1

Related Questions