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.
Related
I have a little function that has a string parameter. Now I want a variable defined within that function to be known outside of that function where the function is being executed.
function somefunc($hello) {
$hello = "hi";
$bye = "bye";
return $bye;
}
And using that function in another php script.
somefunc("hi");
echo $bye;
The other script in which the function is being used and in which I'm trying to echo out the variable keeps telling me that the variable bye has not been defined. How can I get its value without making it global? The other script has the function included in it properly, so this cant be the problem.
Thanks in advance for any help!!
Your syntax is the problem. To fix the current issue you need to first define a variable with the return variable or echo it.
function somefunc($hello) {
$hello = "hi";
$bye = "bye"
return $bye;
}
echo somefunc("hi"); // bye
// --- or ---
$bye = somefunc("hi");
echo $bye; // bye
The variable defined within that function cannot be accessed outside of its context (the function).
The scope of a variable is the context within which it is defined. For the most part all PHP variables only have a single scope. This single scope spans included and required files as well.
For a better understanding of variable scopes check out the docs in the PHP manual; they are pretty good at breaking it down.
You could also look at global references of variable in the PHP manual and it may work for what you are trying to do.
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;
}
?>
I have a bunch of HTML and PHP code and in the template file it works fine but I'm trying to put it in a PHP function and now when I run the page I get the error Undefined variable: variableName
Here's some code:
function testFunction()
{
foreach ($variableName as $variable):
echo 'tasf';
endforeach;
}
Inside that function $variableName cannot be found but if I move it outside the function it can be found just fine. I'm doing this within a symfony php template file if it matters.
Simple issue of variable scope. If that variable is defined outside the function then either you need to pass it there or declare it global
See Manual Here
PHP Variable Scope
$str = 'Hello World';
echo $str; // works fine
function foo($bar){
echo $bar; // passed as function argument. works fine
}
foo($str);
function bar(){
global $str;
echo $str; // passed from global. works fine
}
Function scope means that variables referenced inside a function, must be declared within it, or passed...
function testFunction($variableName)
{
foreach ($variableName as $variable):
echo 'tasf';
endforeach;
}
Here's a link to the PHP manual on Variable Scope.
Under no circumstances should you resort to using global variables. There is always a better way, and doing so is considered poor practice. It makes your code difficult to follow as it means anyone else may have to read all of it in order to understand what's going on.
You need to use the global keyword to make this happen.
global should be used sparingly however, and can have unintended side effects.
I just faced a piece of code which makes it possible accessing the variable by making it global and started thinking if it is different from other language approach/behavior
<?php
$a1 = "WILLIAM";
$a2 = "henry";
$a3 = "gatES";
echo $a1 . " " . $a2 . " " . $a3 . "<br />";
fix_names();
echo $a1 . " " . $a2 . " " . $a3;
function fix_names()
{
global $a1; $a1 = ucfirst(strtolower($a1));
global $a2; $a2 = ucfirst(strtolower($a2));
global $a3; $a3 = ucfirst(strtolower($a3));
}
?>
The code accesses variables defined outside the function and makes them global inside the function. This is unlikely in other languages. For example we write variables in global space in C and make them global, thus we can access them inside function. So we first make them global and then access them everywhere. In above code, we first access them inside the function (also I did not understand how we can access $a1, $a2, $a3 inside function when they are not passed as an argument) and then make them global. Is this because of any different behavior of PHP processor.
Also I did not understand how we can make variables global elsewhere away from its declaration.
Sorry this may not be a question asking exactly where the code is breaking, but I believe understanding why code is written in a particular manner and why it behaves in a particular manner is also important.
Putting it (hopefully) in much cleared words
I want to know: inside a function when we create a global variable with the same name as the variable that already exist in an outer scope, it actually global-izes the variable in outer scope instead of creating a new global variable (with null value). Is it like that? And if yes isn't that different from other languages? So is there any reason behind such distinct behavior?
In php functions has their own scope, thus if you declare the variable elsewhere outside the function it will not visible inside it. To use them inside the function you need to declare it global. Usually, I use Registry pattern to not polute global scope and store all global objects which I will use later.
According to the manual - http://php.net/manual/en/language.variables.scope.php
The scope of a variable is the context within which it is defined. For the most part all PHP variables only have a single scope. This single scope spans included and required files as well.
...
However, within user-defined functions a local function scope is introduced. Any variable used inside a function is by default limited to the local function 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.
This enables you to use the same $var name inside a function, without it reassigning the value-
$var = 'string';
function test(){
$var = 'new string';
return $var;
}
echo $var; // echo's - string
test(); // echo's - new string
Consider using sessions. You can define you variables in file file1.php like this:
session_start();
$_SESSION['a'] = 'William';
Then you can access any session variable in file file2.php like this:
echo $_SESSION['a'];
Please find a nice article on Global variables in php - It will tell you about various global variables that exist in Php Language and how to use and access these variables and their purpose.
Reference : https://www.w3elearners.com/php/global-variables/
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