Greg L
Greg L

Reputation: 468

Defining a global variable, and including functions that require it?

I have six functions that require a global variable. In an attempt to reduce redundancy, I wrote a new function that is triggered rather than triggering all six. This one function has a global $var that is required by the other functions.

So, it looks like this

function one_function_for_the_rest() {
    global $importantVar;

    functionOne();
    functionTwo();
    functionThree();

}

but the global variable is not being seen by the called functions. Am I doing this incorrectly, or is this a limitation I was not aware of?

Upvotes: 0

Views: 67

Answers (3)

bountyh
bountyh

Reputation: 165

You're not doing it correctly as the variable is defined when on_function_for... is called. An easier way for this would be just to have $importantVar; at the start of the code.

Or wrap your functions inside a class and put the variable inside the class.

e: so basically do : function myFunc($important) { stuff } and when calling the function do myFunc($importantVar)

example :

$asd = "lol";
class myclass {

    public function lol($asd) {
        echo $asd;
    }
}
$obj = new myclass;
$obj->lol($asd);

Upvotes: 1

Rouven Weßling
Rouven Weßling

Reputation: 631

PHP does not have the same scoping rules as most other languages have. That is the downside to not having to declare variables with var as in JavaScript or other similar constructs.

Basically in PHP, every function used is only available in that function. There are three exceptions:

  1. The global keyword
  2. The $this variable inside objects. This one is also "magic" as it's also available inside anonymous functions defined inside a class.
  3. When declaring an anonymous functions you can bind variables to it using use.

Upvotes: 1

elixenide
elixenide

Reputation: 44823

You're not doing it correctly. Each function either needs to use the global scope identifier, like global $importantVar;, or have $importantVar passed as a parameter. Otherwise, the other functions don't have $importantVar in their respective scopes.

Simply calling a function from within one_function_for_the_rest does not tell that other function anything about global variables or variables used in one_function_for_the_rest. In technical terms, your function calls do not bring $importantVar into the respective scopes of functionOne, functionTwo, or functionThree.

Upvotes: 1

Related Questions