global variables scope in php - php

I didn't understand this sentence from php.net:
Note:
Using global keyword outside a function is not an error. It can be used if the file is included from inside a function.
what does it mean? can anyone demonstrate briefly?

Global Variables:
In contrast to local variables, a global variable can be accessed in any part of the program. However, in order to be modified, a global variable must be explicitly declared to be global in the function in which it is to be modified. This is accomplished, conveniently enough, by placing the keyword GLOBAL in front of the variable that should be recognized as global. Placing this keyword in front of an already existing variable tells PHP to use the variable having that name.
Example
$somevar = 15;
function addit(){
GLOBAL $somevar;
$somevar++;
print "Somevar is $somevar";
}
addit();
Output
Somevar is 16

"It can be used if the file is included from inside a function" means that it will even work like this:
page.php
<?php
global $d;
$d = "HI";
?>
index.php
<?php
getpage();
function getpage(){
include 'page.php';
echo $d;
}
?>

Related

Why $GLOBAL is not working in function scope - PHP

I have write the code like same two times: on root of the file and in the function
$GLOBAL superglobal variable is not working in the function. But same thing already working in out of fuction
Reference:
1. php_superglobals
2. reserved.variables.globals
Code:
<?php
// working here
$GLOBALS['x'] = "Root of the file";
echo $x;
// same things are not working in the function.
function checkglobal() {
$GLOBALS['z'] = "In the function.";
echo $z;
}
checkglobal();
Output:
Root of the file
NOTICE Undefined variable: z on line number 10
Click and check here
I found my mistake in my code.
$GLOBALS superglobal variable is used for creating global variable and access that in non-global scope.
Need to declare the global variable with "global" keyword, if we want to use directly in non-global scope.
Corrected Code:
<?php
// working here
$GLOBALS['x'] = "Root of the file";
echo $x;
// same things are not working in the function.
function checkglobal() {
$GLOBALS['z'] = "In the function.";
global z; // declare global variable *******************
echo $z;
}
checkglobal();
Output:
Root of the file
In the function.
This script will not produce any output because the echo statement refers to a local version of the $z variable, and it has not been assigned a value within this scope. You may notice that this is a little bit different from the C language in that global variables in C are automatically available to functions unless specifically overridden by a local definition. This can cause some problems in that people may inadvertently change a global variable. In PHP global variables must be declared global inside a function if they are going to be used in that function.

How to use variables from php file where require/include is declared

So basically, I have a config.php file for connecting to the mysql database, and a functions.php file that includes some functions. In all my files (eg. index, login, register), I use the line require('config.php'); and inside config.php I have this line require('functions.php'); for including the config + functions together using the line require('config.php'); in my index, login, and register.php files.
So basically my problem is, the variables that I've declared in config.php are not recognized inside functions.php. How do I make it work?
Thanks in advance.
Use the global statement to declare variables inside functions as global variables.
function myfunction() {
global $myvar; // $myvar set elsewhere can be read within this function
// and if its value changes in this function, it changes globally
}
You can use global variavlename or $GLOBAL['variavlename without $']
<?php
$a = 1;
$b = 2;
function Sum()
{
global $a;
$a = $a + $GLOBALS['b'];
}
Sum();
echo $a;
?>
It's very likely your functions don't work because their scope does not include the variables you are trying to use.
First, make sure functions.php is being included after the variables are set
Also, make your functions Public Functions, OR, declare global variables inside functions by doing this:
$testVariable = "test";
function testFunction() {
global $testVariable;
}

Variable accessibility with require_once/ob_start()

Maybe I'm just tired or just am simply confused, but I'm having a strange issue dealing with some require_once() calls and ob_start().
Basic Structure:
Top of Main.php:
require_once 'config.php'; // includes variable $A = "bar", and Function "foo"
function getPage(){
ob_start();
include 'some_file.php';
$html = ob_get_clean();
echo $html;
die();
}
getPage();
some_file.php
require_once 'config.php'; // includes same config file
var_dump($A); // NULL
foo(); // runs, returns correct value
Config.php
$A = 'bar';
function foo(){
return "FOO";
}
So, what is wrong here? I'm including a file while buffering output. The required file config.php holds a variable and function. When including some_file.php during the buffer, the variable $A is apparently NOT set/accessible. The function foo CAN execute.
The documentation says:
When a file is included, the code it contains inherits the variable
scope of the line on which the include occurs. Any variables available
at that line in the calling file will be available within the called
file, from that point forward. However, all functions and classes
defined in the included file have the global scope.
Your provided code does not illustrate the problem that you're describing. When I run it as-is, it correctly shows that the variable is defined.
That being said, the thing to remember is that what looks like a global variable in an included file actually ends up in the scope of the function that's calling it. So if the first time require_once() is called is from a function, the $A variable is scoped to the function - and disappears when the function returns, just like any other variable defined inside the function.
If you absolutely must define a global variable inside an included file (are you sure? really?), make sure you only include that file from the global scope - not from within a function. If you need to access the variable from within a function, include the file outside the function, and then use the global keyword to access the variable from within the function.

Do I need to use "global" for every variable I use between two different <?php ?> tags?

For example:
<?php $foo = 'blah'; ?>
<?php echo $foo; ?>
Do I need to put a global $foo; before the echo in the second <?php ?>?
Nope, that will work fine as is.
You only need to use global when the variable is accessed in a function/class or otherwise not in the immediate scope it was declared in.
No, you don't. You actually don't even have to use the global keyword if you use the variable in an included file.
E.g.:
file1.php
<?php
$foo = 'a variable';
include 'file2.php';
?>
file2.php
<?php
// here you can use the $foo variable, as it was declared before the inclusion
echo $foo;
?>
In normal situations the only use of "global" keyword is inside of a function's scope and for using a global variable inside the local scope of a function. for example:
<?php
$globalVariable = 2;
function myFunction()
{
global $globalVariable;
return $globalVariable;
}
?>
However, using global keyword outside of a function is allowed, because you may include a file from inside of a function.
No, you do not need to do this.
The use of global keyword is only needed when you're changing the variable scope. There's a chapter in PHP manual, that describes the variable scope and the global keyword. This lecture will help you to understand the topic: Variable scope in PHP manual.

global variables in php not working as expected

I'm having trouble with global variables in php. I have a $screen var set in one file, which requires another file that calls an initSession() defined in yet another file. The initSession() declares global $screen and then processes $screen further down using the value set in the very first script.
How is this possible?
To make things more confusing, if you try to set $screen again then call the initSession(), it uses the value first used once again. The following code will describe the process. Could someone have a go at explaining this?
$screen = "list1.inc"; // From model.php
require "controller.php"; // From model.php
initSession(); // From controller.php
global $screen; // From Include.Session.inc
echo $screen; // prints "list1.inc" // From anywhere
$screen = "delete1.inc"; // From model2.php
require "controller2.php"
initSession();
global $screen;
echo $screen; // prints "list1.inc"
Update:
If I declare $screen global again just before requiring the second model, $screen is updated properly for the initSession() method. Strange.
Global DOES NOT make the variable global. I know it's tricky :-)
Global says that a local variable will be used as if it was a variable with a higher scope.
E.G :
<?php
$var = "test"; // this is accessible in all the rest of the code, even an included one
function foo2()
{
global $var;
echo $var; // this print "test"
$var = 'test2';
}
global $var; // this is totally useless, unless this file is included inside a class or function
function foo()
{
echo $var; // this print nothing, you are using a local var
$var = 'test3';
}
foo();
foo2();
echo $var; // this will print 'test2'
?>
Note that global vars are rarely a good idea. You can code 99.99999% of the time without them and your code is much easier to maintain if you don't have fuzzy scopes. Avoid global if you can.
global $foo doesn't mean "make this variable global, so that everyone can use it". global $foo means "within the scope of this function, use the global variable $foo".
I am assuming from your example that each time, you are referring to $screen from within a function. If so you will need to use global $screen in each function.
You need to put "global $screen" in every function that references it, not just at the top of each file.
If you have a lot of variables you want to access during a task which uses many functions, consider making a 'context' object to hold the stuff:
//We're doing "foo", and we need importantString and relevantObject to do it
$fooContext = new StdClass(); //StdClass is an empty class
$fooContext->importantString = "a very important string";
$fooContext->relevantObject = new RelevantObject();
doFoo($fooContext);
Now just pass this object as a parameter to all the functions. You won't need global variables, and your function signatures stay clean. It's also easy to later replace the empty StdClass with a class that actually has relevant methods in it.
You must declare a variable as global before define values for it.
The global scope spans included and required files, you don't need to use the global keyword unless using the variable from within a function. You could try using the $GLOBALS array instead.
It is useless till it is in the function or a class. Global means that you can use a variable in any part of program. So if the global is not contained in the function or a class there is no use of using Global

Categories