简体   繁体   中英

PHP Variable Scope issue?

I'm writing a function and it uses the $PDO variable in another file. I included the file at the beginning, but it's saying undeclared variable. I'm assuming it's because it's out of scope.

  require './db/db.php';
  session_start();

    function createUser($username) {

    }

What can I do to be able to reference the variable $PDO which is my PDO instance to use the database in my functions?

Assuming you didn't declare the "PDO instance" inside any external function or class, you should just pass it to the function as a parameter. So (if you're talking about your createUser function)

createUser($PDO, $username) { }

And you'd call it like this: createUser($PDO, 'Foo'); .

Pass $PDO as an argument;

function function_name($PDO)
{
    // Your function code
}

Either pass the variable to the function as an argument, or put

global $PDO;

in the function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM