How to assign global variable?

How do you assign a global variable. Is it something like this?


global $variable = "testing";

I’m on php 4.3.11

All variables are global by default (not really “global”, but available to all included files too), except to functions (maybe classes).

To get it to work in a function use something like:


<?php

$var = "foo";
$var2 = "bar";

function printthis() {
global $var, $var2; //Put in vars here

echo $var . $var2;
}

printthis();

?>

See http://php.net/global

All variables assigned outside of functions, classes, objects, etc are applied in the “global” scope.

$a = 1;

$a is now a variable defined in the “global” scope. To access this variable within other functions, etc, I would either pass it to the function itself (preferred IMO), use the “global” keyword within the funtion itself, or my weapon of choice, the $GLOBALS magic array.

$a = 1;

function show_a()
{
	 echo $GLOBALS['a'];
}

show_a();

Hope that helps.

If you want to assign a global variable from within a function:

$bar = 1;

function foo()
{
    global $bar;  // this is important!

    $bar = 2;
}

$GLOBALS can also be used to perform the same function as above. My preference for $GLOBALS exists only because it allows you to keep a very short leash on contaminating global variables with function specific information by mistake. Like if you forget you called a variable from the global scope into your function, and are manipulating it and forget that you’re working with a global variable. It’s gonna be pretty hard to forget you’re working with a global variable if you use the magic $GLOBALS array.

Personal preference and coding standards are an area we are entering into here, and it’s something you should setup for yourself, or find out from the programming lead on the preferred method.

Have fun! :slight_smile:

thank you :slight_smile: