Why is an empty line printed instead of 5?
function test()
{
echo "$a <br/>";
}
$a = 5;
test();
Functions in PHP do not inherit global scope or parent scope (unless using an anonymous function with use()).
You can use the global keyword to access them.
function test()
{
global $a;
echo "$a <br/>";
}
CodePad.
Jared Farish also points out the use of the global associative array $GLOBALS which holds all global variables and which, like any super global such as $_POST, $_GET, etc, is in scope everywhere.
function test()
{
echo "$GLOBALS[a] <br/>";
}
$a = 5;
test();
CodePad.
You could use an anonymous function...
$a = 5;
$test = function() use ($a) {
echo $a;
};
$test();
CodePad.
As a footnote, try not to rely on global variables. They can be a sign of poor program design if you overly rely on them.
you forgot to use the global
function test()
{
global $a;
echo "$a <br/>";
}
$a = 5;
test();
Related
I have code something like this:
<?
$a="localhost";
function body(){
global $a;
echo $a;
}
function head(){
global $a;
echo $a;
}
function footer(){
global $a;
echo $a;
}
?>
is there any way to define the global variable in one place and make the variable $a accessible in all the functions at once? without making use of global $a; more?
The $GLOBALS array can be used instead:
$GLOBALS['a'] = 'localhost';
function body(){
echo $GLOBALS['a'];
}
From the Manual:
An associative array containing references to all variables which are currently defined in the global scope of the script. The variable names are the keys of the array.
If you have a set of functions that need some common variables, a class with properties may be a good choice instead of a global:
class MyTest
{
protected $a;
public function __construct($a)
{
$this->a = $a;
}
public function head()
{
echo $this->a;
}
public function footer()
{
echo $this->a;
}
}
$a = 'localhost';
$obj = new MyTest($a);
If the variable is not going to change you could use define
Example:
define('FOOTER_CONTENT', 'Hello I\'m an awesome footer!');
function footer()
{
echo FOOTER_CONTENT;
}
If a variable is declared outside of a function its already in global scope. So there is no need to declare. But from where you calling this variable must have access to this variable. If you are calling from inside a function you have to use global keyword:
$variable = 5;
function name()
{
global $variable;
$value = $variable + 5;
return $value;
}
Using global keyword outside a function is not an error. If you want to include this file inside a function you can declare the variable as global.
// config.php
global $variable;
$variable = 5;
// other.php
function name()
{
require_once __DIR__ . '/config.php';
}
You can use $GLOBALS as well. It's a superglobal so it has access everywhere.
$GLOBALS['variable'] = 5;
function name()
{
echo $GLOBALS['variable'];
}
Depending on your choice you can choose either.
Add your variables in $GLOBALS super global array like
$GLOBALS['variable'] = 'localhost';
and use it globally as
echo $GLOBALS['variable']
or you can use constant which are accessible throughout the script
define('HOSTNAME', 'localhost');
usage for define (NOTE - without the dollar)
echo HOSTNAME;
This answer is very late but what I do is set a class that holds Booleans, arrays, and integer-initial values as global scope static variables. Any constant strings are defined as such.
define("myconstant", "value");
class globalVars {
static $a = false;
static $b = 0;
static $c = array('first' => 2, 'second' => 5);
}
function test($num) {
if (!globalVars::$a) {
$returnVal = 'The ' . myconstant . ' of ' . $num . ' plus ' . globalVars::$b . ' plus ' . globalVars::$c['second'] . ' is ' . ($num + globalVars::$b + globalVars::$c['second']) . '.';
globalVars::$a = true;
} else {
$returnVal = 'I forgot';
}
return $returnVal;
}
echo test(9); ---> The value of 9 + 0 + 5 is 14.
echo "<br>";
echo globalVars::$a; ----> 1
The static keywords must be present in the class else the vars $a, $b, and $c will not be globally scoped.
You can try the keyword use in Closure functions or Lambdas if this fits your intention... PHP 7.0 though. Not that's its better, but just an alternative.
$foo = "New";
$closure = (function($bar) use ($foo) {
echo "$foo $bar";
})("York");
demo |
info
You can declare global variables as static attributes:
class global {
static $foo = "bar";
}
And you can use and modify it every where you like, like:
function echoFoo() {
echo global::$foo;
}
You answered this in the way you wrote the question - use 'define'. but once set, you can't change a define.
Alternatively, there are tricks with a constant in a class, such as class::constant that you can use. You can also make them variable by declaring static properties to the class, with functions to set the static property if you want to change it.
What if you make use of procedural function instead of variable and call them any where as you.
I usually make a collection of configuration values and put them inside a function with return statement. I just include that where I need to make use of global value and call particular function.
function host()
{
return "localhost";
}
$GLOBALS[] is the right solution, but since we're talking about alternatives, a function can also do this job easily:
function capital() {
return my_var() . ' is the capital of Italy';
}
function my_var() {
return 'Rome';
}
I have code something like this:
<?
$a="localhost";
function body(){
global $a;
echo $a;
}
function head(){
global $a;
echo $a;
}
function footer(){
global $a;
echo $a;
}
?>
is there any way to define the global variable in one place and make the variable $a accessible in all the functions at once? without making use of global $a; more?
The $GLOBALS array can be used instead:
$GLOBALS['a'] = 'localhost';
function body(){
echo $GLOBALS['a'];
}
From the Manual:
An associative array containing references to all variables which are currently defined in the global scope of the script. The variable names are the keys of the array.
If you have a set of functions that need some common variables, a class with properties may be a good choice instead of a global:
class MyTest
{
protected $a;
public function __construct($a)
{
$this->a = $a;
}
public function head()
{
echo $this->a;
}
public function footer()
{
echo $this->a;
}
}
$a = 'localhost';
$obj = new MyTest($a);
If the variable is not going to change you could use define
Example:
define('FOOTER_CONTENT', 'Hello I\'m an awesome footer!');
function footer()
{
echo FOOTER_CONTENT;
}
If a variable is declared outside of a function its already in global scope. So there is no need to declare. But from where you calling this variable must have access to this variable. If you are calling from inside a function you have to use global keyword:
$variable = 5;
function name()
{
global $variable;
$value = $variable + 5;
return $value;
}
Using global keyword outside a function is not an error. If you want to include this file inside a function you can declare the variable as global.
// config.php
global $variable;
$variable = 5;
// other.php
function name()
{
require_once __DIR__ . '/config.php';
}
You can use $GLOBALS as well. It's a superglobal so it has access everywhere.
$GLOBALS['variable'] = 5;
function name()
{
echo $GLOBALS['variable'];
}
Depending on your choice you can choose either.
Add your variables in $GLOBALS super global array like
$GLOBALS['variable'] = 'localhost';
and use it globally as
echo $GLOBALS['variable']
or you can use constant which are accessible throughout the script
define('HOSTNAME', 'localhost');
usage for define (NOTE - without the dollar)
echo HOSTNAME;
This answer is very late but what I do is set a class that holds Booleans, arrays, and integer-initial values as global scope static variables. Any constant strings are defined as such.
define("myconstant", "value");
class globalVars {
static $a = false;
static $b = 0;
static $c = array('first' => 2, 'second' => 5);
}
function test($num) {
if (!globalVars::$a) {
$returnVal = 'The ' . myconstant . ' of ' . $num . ' plus ' . globalVars::$b . ' plus ' . globalVars::$c['second'] . ' is ' . ($num + globalVars::$b + globalVars::$c['second']) . '.';
globalVars::$a = true;
} else {
$returnVal = 'I forgot';
}
return $returnVal;
}
echo test(9); ---> The value of 9 + 0 + 5 is 14.
echo "<br>";
echo globalVars::$a; ----> 1
The static keywords must be present in the class else the vars $a, $b, and $c will not be globally scoped.
You can try the keyword use in Closure functions or Lambdas if this fits your intention... PHP 7.0 though. Not that's its better, but just an alternative.
$foo = "New";
$closure = (function($bar) use ($foo) {
echo "$foo $bar";
})("York");
demo |
info
You can declare global variables as static attributes:
class global {
static $foo = "bar";
}
And you can use and modify it every where you like, like:
function echoFoo() {
echo global::$foo;
}
You answered this in the way you wrote the question - use 'define'. but once set, you can't change a define.
Alternatively, there are tricks with a constant in a class, such as class::constant that you can use. You can also make them variable by declaring static properties to the class, with functions to set the static property if you want to change it.
What if you make use of procedural function instead of variable and call them any where as you.
I usually make a collection of configuration values and put them inside a function with return statement. I just include that where I need to make use of global value and call particular function.
function host()
{
return "localhost";
}
$GLOBALS[] is the right solution, but since we're talking about alternatives, a function can also do this job easily:
function capital() {
return my_var() . ' is the capital of Italy';
}
function my_var() {
return 'Rome';
}
Why is $a not printing?
And what is the alternate of this, and I dont want to use return.
function abc () {
$a = 'abc';
global $a;
}
abc();
echo $a;
The reason why it's not echoing is because of two things:
1) You need to declare global "before" the variable you wish to define as being global.
and
2) You also need to call the function.
Rewrite:
<?php
function abc()
{
global $a;
$a = 'abc';
}
abc();
echo $a;
For more information on variable scopes, visit the PHP.net website:
http://www.php.net/manual/en/language.variables.scope.php
You can get your variable as:
echo $GLOBALS['a'];
see http://php.net/manual/en/language.variables.scope.php
You can use define():
function abc() {
define("A", "abc");
}
abc();
echo A;
Make sure you call the function. I added that just above echo.
First you must create and assign a variable. And then in you function describe that is a global var you want to use.
$a = 'zxc';
function abc() {
global $a;
$a = 'abc';
}
abc();
echo $a;
This is not really good idea to use golbal such way. I don't really understand why I so much want to use a global var...
But my opinion is better for you to use a pointer to variable.
function abc(&$var){
$var = 'abc';
}
$a = 'zxc';
abc(&$a);
echo $a;
Or even would be better to create an object and then access variable with-in this object
Somehow, the following results in NULL. Why is this the case? I find it important to know, because the use statements does not support variable variables.
function a() {
$a = "a";
$aa = function() {
global $a;
var_dump($a);
};
$aa();
}
a();
The value is NULL because there is no global with name $a.
The following would print "global":
$a = "global"; // global variable initialization
function a() {
$a = "a";
$aa = function() {
global $a;
var_dump($a);
};
$aa();
}
a();
You can write this :
function a() {
$a = "a";
function b() {
global $a;
var_dump($a);
};
$aa = "b";
$aa();
}
a();
Maybe you can make a reference to the variable variables.
function a() {
$a = "b";
$b = "variable";
$ref = &$$a;
$aa = function() use ($ref) {
var_dump($ref);
};
$aa();
}
a();
which outputs: string(8) "variable"
Variable $t is the variable variable you can access with $$a. Note that inside the function a(), $t is never used, so should be what you want.
$t = 3;
$a = 't';
function a()
{
global $a, $$a;
$x = $$a;
$b = function() use ($x) {
echo $x;
};
$b();
}
a();
The code prints 3.
global $a access a global variable called $a. It is not the local variable in the function a. Since you have never initialized a global variable called $a, it is NULL.
In order for local variables to be usable inside an anonymous function, they must be captured using a use clause. Local variables can either be captured by value or by reference.
If you want to capture by value (which means the value of the local variable $a is copied into the closure at the time it's defined):
function a() {
$a = "a";
$aa = function() use ($a) {
var_dump($a);
};
$aa();
}
a();
If you want to capture by reference (which means inside the closure it directly references the variable $a):
function a() {
$a = "a";
$aa = function() use (&$a) {
var_dump($a);
};
$aa();
}
a();
In this case both would be the same. But if you modified the variable after the closure was created, and before it is run, it would give a different result (the capture by value would still have the previous value).
Let us ignore the bad design and ponder the use of a variable which is global inside a function, but not global in the default namespace:
a();
function a() {
function b() {
global $x;
echo $x;
}
$x=10;
b();
}
The variable $x is not printed to stdout. However, if we declare global $x inside function a() then it is printed to stdout. Is there any way to define $x as global inside a() (such that it is available in the b() function) yet not in scope in the default namespace?
Edit: Assume that there is an arbitrarily large number of variables to pass, as such defining them with use() or as parameters is not practical.
Ignoring bad design or why you're not just passing this as a param, you can use a closure and an anonymous function, if you define the arguments before you define the function:
function a() {
$x = 10;
$b = function() use($x) {
echo $x; // 10
};
$b();
}
a();
echo $x; // Undefined variable