确保MySQL连接在PHP函数中有效

I have code with the following form:

<?php
function doSomething{
  //Do stuff with MySQL
  $con->tralalala();
}
$con = connectToDatabase;//This would actually be a line or two.
doSomething();
?>

This (type of) code doesn't work, because doSomething() doesn't have a connection to the database. Can anyone explain why not? I create the $con connection before I call doSomething(). So why does the function act as if there's no connection?

Is there any way to fix this, short of passing the connection into the function like doSomething($con)?

you probably need to tell it to look in the global scope:


     function doSomething()
     {
         global $con;
         $con->tralalala();
     }