I am facing some errors with use of global variables. I defined a $var in global scope and trying to use it in functions but it not accessible there. Please see below code for better explanation:
File a.php:
<?php
$tmp = "testing";
function testFunction(){
global $tmp;
echo($tmp);
}
So a bit about how this function is called.
File b.php:
<?php
include 'a.php'
class testClass{
public function testFunctionCall(){
testFunction();
}
}
The above 'b.php' is called using:
$method = new ReflectionMethod($this, $method);
$method->invoke();
Now the desired output is 'testing' but the output received is NULL.
Thanks in advance for any help.
Global variables refer to any variable that is defined outside of the function. Global variables can be accessed from any part of the script i.e. inside and outside of the function. So, a global variable can be declared just like other variable but it must be declared outside of function definition.
Some predefined variables in PHP are "superglobals", which means that they are always accessible, regardless of scope - and you can access them from any function, class or file without having to do anything special. The PHP superglobal variables are: $GLOBALS.
Global variables can be altered by any part of the code, making it difficult to remember or reason about every possible use. A global variable can have no access control. It can not be limited to some parts of the program. Using global variables causes very tight coupling of code.
Global is used to get the global vars which may be defined in other scripts, or not in the same scope. e.g. Static is used to define an var which has whole script life, and init only once.
You missed calling your function and also remove the protected
keyword.
Try this way
<?php
$tmp = "testing";
testFunction(); // you missed this
function testFunction(){ //removed protected
global $tmp;
echo($tmp);
}
Same code but using $GLOBALS
, gets you the same output.
<?php
$tmp = "testing";
testFunction(); // you missed this
function testFunction(){ //removed protected
echo $GLOBALS['tmp'];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With