I know I can use $GLOBALS['var'] inside a function to refer to variables in the global scope.
Is there anyway I can use some kind of a declaration inside the function so I will be able to use $var without having to use $GLOBAL['var'] every time?
Joel
Although it's not recommended, but if you do want to, here's what you can do:
If you only want to GET the values from the vars (and not SET the values), just use extract:
extract($GLOBALS);
This will extract and create all the variables in the current scope.
How about using static class?
such as
class example
{
public static $global;
public static function set($arr)
{
foreach ($arr as $key=>$val)
{
self::$global[$key] = $val;
}
}
}
function example_function()
{
var_dump( example::$global );
}
example::set( array('a'=>1, 'b'=>2) );
example_function();
You can use the global keyword, So you can use type $var instead of $GLOBALS['var'] inside a function.
function myFunc() {
global $var;
$var = 3;
}
$var = 1;
myFunc();
echo $var;
Output: 3
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';
}
As of now I create a variable like this in a file that's loaded on all pages:
<?php
add_action( 'parse_query', 'my_global_vars' );
function my_global_vars() {
/* CUSTOM GLOBAL VARIABLES */
$variable_name = get_query_var('category_name');
}
?>
And every time I want to use it (in other files), I must do it like this:
<?php
global $variable_name;
if( $variable_name = 'news' ){
// Do something
}
?>
And when I need to use the variable multiple times in the same file, I add global $variable_name; at the top of the file, and simply use $variable_name in rest of the instances.
But as the number of variables increase, I find it harder to manage the list of global $variable_names at the top of all files.
Is there a way to define a variable as global at the time of creation and simply use $variable_name everywhere else?
EDIT: One way is to define variable like this:
<?php
add_action( 'parse_query', 'my_global_vars' );
function my_global_vars() {
/* CUSTOM GLOBAL VARIABLES */
global $variable_name;
$variable_name = get_query_var('category_name');
}
?>
And use it like using $GLOBALS[] like this $GLOBALS['variable_name'] elsewhere.
Having a lot of global vars is usually bad. It becomes a mess very quickly.
If you really need global variables the best approach is to use static class variables. They are just as global as the others, but they enforce better naming and pre-declaration so the end result is somewhat better.
If you really need normal global vars you can also use the $GLOBALS variable, it is available in every scope and is basically an array of all the global variables.
global $variable_name;
do_something_with($variable_name);
is the same as
do_something_with($GLOBALS['variable_name']);
You can use a static class for this and keep it OOP:
<?php
class GlobalVariables {
private static $vars = array();
public static function get($name, $default = null) {
return (isset(self::$vars[$name]) ? self::$vars[$name] : $default);
}
public static function set($name, $value) {
self::$vars[$name] = $value;
}
}
function foo() {
GlobalVariables::set('foo', 'oof');
}
function bar() {
var_dump( GlobalVariables::get('foo') );
}
foo();
bar(); //oof
?>
DEMO
Alternatively, you can use a Singleton pattern:
<?php
class GlobalVariables {
private static $instance;
private $vars = array();
public static function get() {
if (empty(self::$instance)) {
self::$instance = new GlobalVariables();
}
return self::$instance;
}
public function __get($name) {
return (isset($this->vars[$name]) ? $this->vars[$name] : null);
}
public function __set($name, $value) {
$this->vars[$name] = $value;
}
}
function foo() {
GlobalVariables::get()->foo = 'oof';
}
function bar() {
var_dump( GlobalVariables::get()->foo );
}
foo();
bar(); //oof
?>
DEMO.
Use whichever you find most readable.
GlobalVariables::set('key', 'value');
GlobalVariables::get('key');
or
GlobalVariables::get()->key = 'value';
GlobalVariables::get()->key;
Completely alternatively, if you hate dynamicness, simply use static variables (this, however, requires you to create all variables beforehand):
<?php
class GlobalVariables {
public static $foo;
}
GlobalVariables::$foo = 'oof';
var_dump( GlobalVariables::$foo );
?>
Using global outside a function doesn't do anything. It's meant for inside functions. You can simply remove your global statements.
Edit: I suggest that you try to reduce the number of global variables you have by structuring them. Group them into arrays or objects. E.g., instead of user_name, user_id, user_is_admin, prefer user['name'], user['id'], user['is_admin'], then you only have one variable (user) to declare as global instead of three.
I have two PHP files. In the first I set a cookie based on a $_GET value, and then call a function which then sends this value on to the other file. This is some code which I'm using in join.php:
include('inc/processJoin.php');
setcookie("site_Referral", $_GET['rid'], time()+10000);
$joinProc = new processJoin();
$joinProc->grabReferral($_COOKIE["site_Referral"]);
The other file (processJoin.php) will then send this value (among others) to further files which will process and insert the data into the database.
The problem I'm having is that when the grabReferral() function in processJoin.php is called, the $referralID variable isn't being defined on a global scale - other functions in processJoin.php can't seem to access it to send to other files/processes.
I've tried this in processJoin.php:
grabReferral($rid) {
global $ref_id;
$ref_id = $rid;
}
someOtherFunction() {
sendValue($ref_id);
}
But the someOtherFunction can't seem to access or use the $ref_id value. I've also tried using define() to no avail. What am I doing wrong?
you have to define the global var in the second function as well..
// global scope
$ref_id = 1;
grabReferral($rid){
global $ref_id;
$ref_id = $rid;
}
someOtherFunction(){
global $ref_id;
sendValue($ref_id);
}
felix
personally, I would recommend the $GLOBALS super variable.
function foo(){
$GLOBALS['foobar'] = 'foobar';
}
function bar(){
echo $GLOBALS['foobar'];
}
foo();
bar();
DEMO
This is a simple and working code to initialize global variable from a function :
function doit()
{
$GLOBALS['val'] = 'bar';
}
doit();
echo $val;
Gives the output as :
bar
The following works.
<?php
foo();
bar();
function foo()
{
global $jabberwocky;
$jabberwocky="Jabberwocky<br>";
bar();
}
function bar()
{
global $jabberwocky;
echo $jabberwocky;
}
?>
to produce:
Jabberwocky
Jabberwocky
So it seems that a variable first declared as global inside a function and then initalised inside that function acquires global scope.
The global keyword lets you access a global variable, not create one. Global variables are the ones created in the outermost scope (i.e. not inside a function or class), and are not accessible inside function unless you declare them with global.
Disclaimer: none of this code was tested, but it definitely gets the point across.
Choose a name for the variable you want to be available in the global scope.
Within the function, assign a value to the name index of the $GLOBALS array.
function my_function(){
//...
$GLOBALS['myGlobalVariable'] = 42; //globalize variable
//...
}
Now when you want to access the variable from code running in the global scope, i.e. NOT within a function, you can simply use $ name to access it, without referencing the $GLOBALS array.
<?php
//<global scope>
echo $myGlobalVariable; //outputs "42"
//</global scope>
?>
To access your global variable from a non-global scope such as a function or an object, you have two options:
Access it through the appropriate index of the $GLOBALS array. Ex: $GLOBALS['myGlobalVariable'] This takes a long time to type, especially if you need to use the global variable multiple times in your non-global scope.
A more concise way is to import your global variable into the local scope by using the 'global' statement. After using this statement, you can reference the global variable as though it were a local variable. Changes you make to the variable will be reflected globally.
//<non global scopes>
function a(){
//...
global $myGlobalVariable;
echo $myGlobalVariable; // outputs "42"
//...
}
function b(){
//...
echo $GLOBALS['myGlobalVariable']; // outputs "42"
echo $myGlobalVariable; // outputs "" (nothing)
// ^also generates warning - variable not defined
//...
}
//</non global scopes>
Please use global variables in any language with caution, especially in PHP.
See the following resources for discussion of global variables:
http://chateau-logic.com/content/dangers-global-variables-revisited-because-php
http://c2.com/cgi/wiki?GlobalVariablesAreBad
The visibility of a variable
I hope that helped
<?php
$a = 1;
$b = 2;
function Sum()
{
global $a, $b;
$b = $a + $b;
}
Sum();
echo $b;
?>
I am trying to change a variable that is outside of a function, from within a function. Because if the date that the function is checking is over a certain amount I need it to change the year for the date in the beginning of the code.
$var = "01-01-10";
function checkdate(){
if("Condition"){
$var = "01-01-11";
}
}
A. Use the global keyword to import from the application scope.
$var = "01-01-10";
function checkdate(){
global $var;
if("Condition"){
$var = "01-01-11";
}
}
checkdate();
B. Use the $GLOBALS array.
$var = "01-01-10";
function checkdate(){
if("Condition"){
$GLOBALS['var'] = "01-01-11";
}
}
checkdate();
C. Pass the variable by reference.
$var = "01-01-10";
function checkdate(&$funcVar){
if("Condition"){
$funcVar = "01-01-11";
}
}
checkdate($var);
Just use the global keyword like so:
$var = "01-01-10";
function checkdate(){
global $var;
if("Condition"){
$var = "01-01-11";
}
}
Any reference to that variable will be to the global one then.
All the answers here are good, but... are you sure you want to do this?
Changing global variables from within functions is generally a bad idea, because it can very easily cause spaghetti code to happen, wherein variables are being changed all over the system, functions are interdependent on each other, etc. It's a real mess.
Please allow me to suggest a few alternatives:
1) Object-oriented programming
2) Having the function return a value, which is assigned by the caller.
e.g. $var = checkdate();
3) Having the value stored in an array that is passed into the function by reference
function checkdate(&$values) {
if (condition) {
$values["date"] = "01-01-11";
}
}
Hope this helps.
Try this pass by reference
$var = "01-01-10";
function checkdate(&$funcVar){
if("Condition"){
$funcVar = "01-01-11";
}
}
checkdate($var);
or Try this same as the above, keeping the function as same.
$var = "01-01-10";
function checkdate($funcVar){
if("Condition"){
$funcVar = "01-01-11";
}
}
checkdate(&$var);