0

inside of a function i have a $connection var what obviously stores my connection to mysql, how can i call that var from inside other functions to save me having to paste the $connection var inside of every function that requires this var?

i have tried global to no avail.

many thanks

4 Answers 4

4

You could use the old global keyword.

function a() {
   global $connection;
}

Or you could throw it in $GLOBALS (this will help you get it out of the function defined it in).

Neither of them are too pretty.

Or you could pass in the $connection as an argument.

The most common way of dealing with a database connection is to have its creation handled by a singleton pattern, or have a base class with OO that has a $this->db available, that all your other classes can inherit from.

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

1 Comment

+1 Although it's funny you mention the singleton pattern, because it is very similar to a global variable... ;)
0

Pass the connection as a parameter to the functions that need it. It keeps your code clean and re-usable.

Comments

0

Another solution would be to use a class and make the connection a class variable. You will just use $this->connection every time you need this, but this is not really a solution if you already have a lot of code written in a lot of files.

Comments

0

Declare the variable outside the function, then make it accessible inside each function you need it by using the global keyword.

$globalName = "Zoe";

function sayHello() {
  $localName = "Harry";
  echo "Hello, $localName!";

  global $globalName;
  echo "Hello, $globalName!";
}

sayHello();

stolen from http://www.elated.com/articles/php-variable-scope-all-you-need-to-know/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.