views:

263

answers:

2

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

+5  A: 

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


     function doSomething()
     {
         global $con;
         $con->tralalala();
     }
Andy
Beautiful. Thanks.
stalepretzel
A: 

Andy is technically right, but his implementation should be in a local scope.

This is the way it should be:

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

$connection = connectToDatabase; //This would actually be a line or two.

// Now you can run doSommething() on 
// two database(-connections) in the same session!
doSomething($connection);
Wimmer
I agree it's a crappy solution and the global keyword should be avoided. But that's not what the guy asked, hence my answer. stalepretzel already mentioned the solution you provided.
Andy
Don't give sub-optimal solutions. Simple. PHP is already full of bad code. Let's provide good cut'n paste code.
Wimmer
I agree. Global variables in PHP proliferate too easily.
staticsan
I think you need to look at the question again, willem.ratus. There's no option for cut'n paste code in this case. Unless you haven't noticed, this is a highly abstracted question.
Andy