Andrew
Andrew

Reputation: 238697

PHP syntax question: global $argv, $argc;

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?

Upvotes: 2

Views: 6635

Answers (4)

Anthony Forloney
Anthony Forloney

Reputation: 91786

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;

Upvotes: 3

Lotus Notes
Lotus Notes

Reputation: 6363

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;

Upvotes: 2

Amber
Amber

Reputation: 526583

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

Upvotes: 3

chmod222
chmod222

Reputation: 5722

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

Upvotes: 1

Related Questions