This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
what is the difference between “GLOBAL” and “STATIC” variable in php
if we create a static variable inside a function, this variable exists in further using of the function... and as far as I know global variable does the same.
now what's the benefit of using static variables?
The lexical scope of a static static variable is restricted to the function body – you cannot access the variable outside the function.
However, its value will be remembered across multiple calls of the same function.
Global variables exist in global scope and can be accessed from anywhere in your code (you have to use the global keyword or $GLOBALS array inside functions though)
A static variable just implies that the var belongs to a class but can be referenced without having to instantiate said class. A global var lives in the global namespace and can be referenced by any function in any class. Global vars are always frowned upon because they're so easily misused, overwritten, accidentally referenced, etc. At least with static vars you need to reference via Class::var;
Related
I have heard using global variables is not good, however I am just trying to understand how the PHP language works. I am a beginner in the coding world.
Why can global variables be created within functions? Whether it is through the use of the global keyword or through a superglobal variable. I thought these two actions were used to access global variables in a function. I thought the only way you can create a global variable is to create it outside a function; in the global scope. I have looked at many different websites including w3schools.com and php.net
This is just some simple code I created to try and understand the way global variables work with functions:
<?php
function sample1() {
global $a;
echo $a = "this ";
}
sample1();
function sample2() {
echo $GLOBALS['$b'] = "is ";
}
sample2();
function sample3() {
global $c;
$c = "an ";
}
sample3();
echo $c;
function sample4() {
$GLOBALS['$d'] = "example ";
}
sample4();
echo $GLOBALS['$d'];
?>
This is the result of the code:
this is an example
All of the code works, but I don't understand how I created a global variable on any of these blocks of code? The global variables were not created outside of the functions. How can they be created inside of a function? What am I missing? Any response is appreciated - If possible, please keep the answer simple - I would like to discuss this further in the comment section, because I'm sure I will have follow up questions - Thank you
Variables can be created in the global scope in the two ways you just did - there's nothing saying that a function can't create (or change) a variable in the global scope - WHEN you explicitly ask for it through $GLOBALS or the global keyword.
The issue is that your belief "I thought the only way you can create a global variable is to create it outside a function; in the global scope." is not an exact statement. When you're using $GLOBALS and global, you're referring to the global scope. You're introducing a reference to the global scope inside your function.
With global you're in effect linking the local reference to the global reference, while with $GLOBALS you're explicitly referencing the global scope (which internally inside PHP can be introduced to the local scope in the same way).
In that case you're explicitly saying "I want this variable to be available in the global scope, make it so!" and PHP does what you're asking it to. This behaviour differ between languages, but as you've discovered for PHP, it's allowed.
It's not something I would recommend using in any way - it makes your code very hard to follow and argue around, so consider it an esoteric detail.
I'm working through debugging some legacy code, and want to use a pre-built function that is essentially a wrapper for get_defined_vars().
Running this code directly in the calling file prints an array of variables as expected:
print_r(get_defined_vars());
However, wrapping this in a simplified version of my function prints an empty array:
function debugAllVars() {
print_r(get_defined_vars());
}
debugAllVars();
Regardless of the scope, I would have expected "superglobal" variables such as $_POST to be present in the output.
Why is the output completely empty?
get_defined_vars() prints all variables in the "symbol table" of the scope where it is called. When you try to wrap it as debugAllVars, you introduce a new scope, which has a new symbol table.
For a standalone function like this, the symbol table consists of:
the function's parameters
any global variables imported into the current scope using the global keyword
any static variables declared in the current scope with the static keyword (even if not assigned a value)
any variables implicitly declared by assigning a value to them
any variables implicitly declared by taking a reference to them (e.g. $foo = &$bar would implicitly declare $bar if not already defined; $foo = $bar would not)
Notably, this list does not include the superglobals, such as $_GET, $_POST, and $GLOBALS. If you run get_defined_vars() in global scope (i.e. outside any function), you will see that these are present in the symbol table there, which is also what the magic variable $GLOBALS points to. So, why are they not present in every scope, and how can we use them if they're not?
For this, we need to dig into the internals of the implementation, where these variables are referred to as "auto-globals" rather than "superglobals".
The answer to why is performance: the naive implementation of an "auto-global" would be one that acted as though every function automatically had a line at the top reading global $_GET, $_POST, ...;. However, this would mean copying all those variables into the symbol table before every function was run, even if they weren't used.
So instead, these variables are special-cased in the compiler, while converting your PHP code into the internal "opcodes" used by the VM which executes the code.
Using a source code browser, we can see how this works.
The key function is zend_is_auto_global in zend_compile.c (taken from current master, effectively PHP 7.2):
zend_bool zend_is_auto_global(zend_string *name) /* {{{ */
{
zend_auto_global *auto_global;
if ((auto_global = zend_hash_find_ptr(CG(auto_globals), name)) != NULL) {
if (auto_global->armed) {
auto_global->armed = auto_global->auto_global_callback(auto_global->name);
}
return 1;
}
return 0;
}
Here, name is the name of a variable, and CG means "compiler globals", so the main job of this function is to say "if the variable name given is in a compiler-global hash called auto_globals, return 1". The additional call to auto_global_callback allows the variable to be "lazy loaded", and only populated when it is first referenced.
The main usage of that function appears to be this conditional, in zend_compile_simple_var_no_cv:
if (name_node.op_type == IS_CONST &&
zend_is_auto_global(Z_STR(name_node.u.constant))) {
opline->extended_value = ZEND_FETCH_GLOBAL;
} else {
opline->extended_value = ZEND_FETCH_LOCAL;
}
In other words, if the variable name you referenced is in the list of superglobals, the compiler switches the opcode into a different mode, so that when it is executed, it looks up the variable globally rather than locally.
get_defined_vars gets all variables defined in the scope that it's called in. Your debugAllVars function introduces a new scope, so get_defined_vars will at most give you all variables within debugAllVars. It cannot give you variables from the caller's scope.
Also see Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?.
This question already has answers here:
Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?
(3 answers)
Closed 7 years ago.
I declared a new variable $var at the top of my document. Afterwards, I called a function which should output this variable.
Unfortunately, I get the following message:
Notice: Undefined variable: var
This is my code:
$var = "abc";
func ();
function func() {
echo $var;
}
In PHP, functions cannot access variables that are within the global scope unless the keyword global is used to 'import' the variable into the function's scope.
You would fix it by doing this:
function func() {
global $var;
echo $var;
}
Read more about scoping here: http://php.net/manual/en/language.variables.scope.php
Any variable used inside a function is by default limited to the local function scope.
In PHP global variables must be declared global inside a function if they are going to be used in that function.
Global variables can also be accessed using $GLOBALS although I would avoid using that unless absolutely necessary.
A second way to access variables from the global scope is to use the special PHP-defined $GLOBALS array.
Worth mentioning:
It's worth linking to this discussion on globals and why you may not want to use them: Globals are evil
. I'd say there is a preference to use classes instead, or simply pass in the variable as an argument to the function. I won't say not to use globals but at the very least be mindful of its use.
This is because the scope of the variable, either you define it as global, or you pass it as a parameter.
Check the comments under this post:
Variables Scope
The scoping of your variable is wrong. You will need to either pass it as a function parameter or declare it as Global in the function. Please review function scoping.
You could do something like this:
$var = "abc";
func ();
function func() {
global var;
echo $var;
}
This question already has answers here:
`static` keyword inside function?
(7 answers)
Closed 9 years ago.
I have seen in 3rd party code a variable declared as static, but outside of any class, simply in a "normal" function.
<?php
function doStuff(){
static $something = null;
}
?>
I have never seen static used this way, and I cannot find anything it in the PHP documentation.
Is this legal PHP code? Is this effectively the same as a global variable? If not, what is the purpose?
From the manual:
Another important feature of variable scoping is the static variable.
A static variable exists only in a local function scope, but it does
not lose its value when program execution leaves this scope.
<?php
function test()
{
static $a = 0;
echo $a;
$a++;
}
?>
Now, $a is initialized only in first call of function and every time
the test() function is called it will print the value of $a and
increment it.
Consider the following situation..
$var = 'Lots of information';
function go($var) {
// Do stuff
}
Now, when PHP exits the function, does it clear the memory automatically of all local variables within the function or should I be doing:
unset($var);
...within the function on any local variables that store large amounts of data?
It will clear itself inside the function scope. This means that the $var parameter of the function will no longer exists after the function call.
Notice that $var = 'Lots of information'; is outside the function block therefore will not be cleared automatically. In this case $var in the global scope and $var in the function scope are two different things and inside the function block only $var in the function scope will exists.
This question goes to the concept of Variable Scope. Inside the function, the variables are "contained" and unless declared global, are not related to variables of the same name outside of the function. So if you created a large variable inside a function, and you want to unset() it, you would need to unset() inside the function. This page is important, especially the part about "global" and "static" variables. PHP also has a way to pass a variable by reference using an ampersand in front of the variable name. In that case, the function is operating on the variable itself, not the function's copy of the variable.
http://php.net/manual/en/language.variables.scope.php