Here is a shortened version of my code:
<?php
$foo = "Bar";
function test () {
echo $foo; // Undefined variable?
}
test();
?>
I don't understand, why PHP says, that $foo is undefined. And I always find solutions for deactivating the error reporting, but I want to fix my code. What am I missing?
In PHP you cannot access global variables from functions unless you explicitly import them using global $foo;.
$foo = "Bar";
function test() {
global $foo;
echo $foo;
}
test();
Another option would be accessing it as $GLOBALS['foo'] - $GLOBALS is a special array that "contains" the global scope and is available wverywhere.
However, using global variables is usually a bad idea that results in spaghetti code. Try to avoid them. Usually the correct way is to make the variable a function argument:
function test($foo) {
echo $foo;
}
test('bar');
<?php
$foo = "Bar";
function test ($foo) {
echo $foo; // Now it's defined, as it's passed to the function.
}
test($foo);
?>
It is outside the scope of the function, therefor it does not know it exists.
Don't listen to them telling you to use global - it's not good practice, and will really clutter up your global array (and potentially cause security risks depending on what you toss in there).
Pass the parameters as arguments. This is the correct way.
In the function test, $foo is currently regarded as a local variable. But you didn't defined such a local variable in this method.
What you want, is to use the variable $foo defined outside this function. Hence you want to use a global variable. So you should declare it as such, ie, using global $foo in your function test.
You may want to read http://www.php.net/manual/en/language.variables.scope.php to get a better understanding of this concept.
add a global $foo on your function
$foo = "Bar";
function test () {
global $foo;
echo $foo; // Undefined variable?
}
test();
It seems you need some more tutorials... This is the basics of programming languages:
http://www.php.net/manual/en/language.variables.scope.php
You should pass you variable as parameter (in some cases, global variable can be used but rarely).
Related
This question seems simple enough, but I can't find an answer anywhere...
At the beginning of my php script/file I want to create a variable.
$variable = 'this is my variable';
I want this variable to be available within the entire script, so that all classes, methods, functions, included scripts, etc. can simple call this variable as $variable.
Class MyClass
{
public function showvariable()
{
echo $variable;
}
}
The $_SESSION, $_POST, $_GET variables all behave like that. I can just write a method and use $_POST and it'll work. but if I use $variable, which I have defined at the beginning of my script, it says "Notice: Undefined variable: variable in ..." It even says it, when I write a function, rather than a class method...
I tried to write
global $variable = 'this is my variable';
But then the script wouldn't load...
"HTTP Error 500 (Internal Server Error): An unexpected condition was encountered while the server was attempting to fulfill the request."
How can I make a variable truly globally accessible like $_POST?
Why would I need this? I specifically plan on using it as a form token. At the top of the page I generate my form token as $token, at the bottom of the page I store it in the session. Before handling any form I check if the SESSION token matches the POST token... And since I often have multiple forms on the page (login form in the top nav, and register form in the main body) i just wanna make it convenient and call $token on each form. Sometimes my formelements are generated by classes or functions, but they don't recognize the variable and say it's not defined.
I found it... -.- I thought it would be easy enough...
I have to call to the variable by using
$GLOBALS['variable'];
Just found it... finally...
http://php.net/manual/en/reserved.variables.globals.php
EDIT like 8 months later or so:
I just learned about CONSTANTS!
define('name', 'value');
They just can't be reassigned...
I guess I could use that, too!
http://www.php.net/manual/en/language.constants.php
Just define a variable outside of any class or function. Then use keyword global inside any class or function.
<?php
// start of code
$my_var = 'Hellow Orld';
function myfunc() {
global $my_var;
echo $my_var; // echoes 'Hellow Orld';
}
function myOtherFunc() {
var $my_var;
echo $my_var; // echoes nothing, because $my_var is an undefined local variable.
}
class myClass {
public function myFunc() {
global $my_var;
echo $my_var; // echoes 'Hellow Orld';
}
public function myOtherFunc() {
var $my_var;
echo $my_var; // echoes nothing.
}
}
myFunc(); // "Hellow Orld"
myOtherFunc(); // no output
myClass->myFunc(); // "Hellow Orld"
myClass->myOtherFunc(); // no output
// end of file
?>
you need to declare global to access it in any function scope:
at the top of your script:
global $var;
$var= "this is my variable";
in your class
...
public function showvariable(){
global $var;
echo $var;
}
...
In PHP, global variables must be declared as such within each function in which they will be used. See: PHP Manual, section on variable scope
That being said, global variables are often a bad idea, and in most cases there's a way to avoid their use.
How can we pass the variable value to function without using any parameter? Once we run the script variable value can be echo within the function.
You could use the keyword global, although I think you shouldn't.
Example:
$a = 'foo';
bar();
function bar(){
global $a;
echo $a;
}
Above code will print "foo";
Again, I really think you should not use this and come up with some other implementation that doesn't require the use of global variables.
You can access the value of variable by declaring the variable as global variable.
Lets say I have this:
function myFunc()
{
global $distinct_variable;
die ($distinct_variable);
}
function anotherFunc()
{
$distinct_variable = 'Hello World';
myFunc();
}
anotherFunc();
For anotherFunc() to correctly show 'Hello World', it must be written like this
{
global $distinct_variable;
$distinct_variable = 'Hello World';
myFunc();
}
Now it will show the message, but why must I global $distinct_variable; in anotherFunc() since it is a global in myFunc() which is within anotherFunc()
Yes, I know that variables inside functions won't go outside of them, but I was thinking it should have worked...
Could someone explain why isn't it working?
Thanks.
Thank you for your answers, I get it now :)
A global variable is exactly that - it exists in the GLOBAL scope ONLY.
Everything in PHP (except superglobals) exist in only one scope - be that the global scope, or the scope of a function/method. Scope does not cascade - so just because you have a variable in an "outer" function does not make it available to an "inner" function.
Similarly, global fetches the variables defined in the GLOBAL scope only (the top-most scope), not simply "the scope above this one, from which I was called". This is what you tried to do, but it absolutely will not work. This level of finer-grained control is what function arguments/return values are for.
Each function has its own symbol table. There is also a global symbol table. Just because one function is being called from within another doesn't mean that the variables declared global in one are global in the other, or inherited from the other. They still refer to the variable in the "local" symbol table by default.
Doing global $somevar; echo $somevar boils down to echo $GLOBALS['somevar'];. That $GLOBALS superglobal does not include variables that were defined inside a function: only truly 'global' vars, which exist at the top level of the script.
<?php
$foo = 1;
function meh(){
// <-- $foo can't be accessed
}
It doesn't look like a global variable. However, does it have disadvantages like global stuff if it's outside the function?
All variables defined outside any function are declared in global scope. If you want to access a global variable you have two choices:
Use the global keyword
<?php
$a = 1;
$b = 2;
function Sum()
{
global $a, $b;
$b = $a + $b;
}
?>
Or use the $GLOBALS
<?php
$a = 1;
$b = 2;
function Sum()
{
$GLOBALS['b'] = $GLOBALS['a'] + $GLOBALS['b'];
}
?>
Read more at http://php.net/manual/en/language.variables.scope.php
Yes. They can be accessed from any location, including other scripts. They are slightly better as you have to used the global keyword to access them from within a function, which gives more clarity as to where they are coming from and what they do.
The disadvantages of global variables apply, but this doesn't instantly make them evil as is often perceived in some OO languages. If they produce a good solution that's efficient and easily understandable, then you're fine. There are literally millions of succesful PHP projects that use global variables declared like this. The biggest mistake you can make is not using them and making your code even more complicated when it would have been perfectly fine to use them in the first place. :D
<?php
$foo = 1;
function meh(){
global $foo;
// <-- $foo now can be accessed
}
?>
Outside of the function is sorta like global scope (when compared to C-like languages), but you have to do one thing to allow access to the var within a function:
function meh(){
global $foo;
// $foo now exists in this scope
}
In your example $foo gets created as variable in the global scope. (Unless your shown script was included() from within another functions/methods scope.)
PHP doesn't have real global variables. You have to manually alias it using the global $foo; statement to access them. (Also the "anything global is bad" advise is just that, bad advise.)
If I understand your question correctly, there really shouldn't be a problem. Unless you declare a variable as a global, it will been limited to the scope in which it is declared, in this case whatever php file the above code is defined in. You could declare another variable $foo in meh() and it would be independent of the $foo defined outside.
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