tags:

views:

133

answers:

4

So I have a PHPUnit test, and found this code within a function.

global $argv, $argc;
echo $argc;
print_r($argv);

I understand what these variables represent (arguments passed from the command line), but I've never seen this syntax before:global $argv, $argc;

What specifically is going on here?

A: 

The global keyword makes the specified variables.. well, global variables, accessible from anywhere in that file.

LukeN
Not exactly. `global $a` within a function `foo` doesn't automatically make `$a` refer to the same global within another function `bar`. Instead the `global` keyword more makes a given name refer to the global version within the scope which the `global` keyword is used.
Amber
+1  A: 

The global keyword tells PHP to use the global scope version of a variable and make it visible to the current scope as well, so that variables declared outside functions/classes can be accessed within them too.

Otherwise, trying to read/assign those variables would operate on a different local version of them instead.

Compare:

$foo = 1;

function test() {
    $foo = 2;
}

echo $foo; // prints 1

versus...

$foo = 1;

function test() {
    global $foo;
    $foo = 2;
}

echo $foo; // prints 2
Amber
thanks, that's helpful, but the thing that I am confused about is that those variables are already defined. I'm not defining them. Also, the comma separating $argv, $argc. I haven't seen that before.
Andrew
it is just making the vars globals. By making it globals, you can use the variables in functions as Dav stated
ggfan
Basically Andrew, PHP has done the `$foo = 1;` in the above examples automatically; the `global` keyword is just used like in the functions above to access the global variables PHP has defined in a scope that isn't already global.
Amber
+1  A: 

argv and arc are the parameters passed when running a PHP script from the command line. As far as I'm aware these variables should never appear using HTTP.

See: argc and argv entries in the PHP manual.

The others already explained what global means. The comma simply groups similar declarations.

For example, this line would declare a bunch of private variables for a class:

private $name, $email, $datejoined;

which is the same thing as writing:

private $name;
private $email;
private $datejoined;
Lotus Notes
+1  A: 

In languages like Java, they allow you declare multiple variables of the same type on one line separated by a comma.

int sum, counter, days, number;

Without an IDE to test the code, I would say its the same regards to PHP, it just declares those two variables as global. You could write them separately on two seperate lines,

global $argv;
global $argc;
Anthony Forloney