开发者

make a variable inside a function accessible to other functions?

开发者 https://www.devze.com 2023-01-31 00:21 出处:网络
inside of a function i have a $connection var wh开发者_StackOverflow中文版at obviously stores my connection to mysql,

inside of a function i have a $connection var wh开发者_StackOverflow中文版at 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


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.


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


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.


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/

0

精彩评论

暂无评论...
验证码 换一张
取 消