开发者

PHP syntax question: global $argv, $argc;

开发者 https://www.devze.com 2022-12-29 07:08 出处:网络
So I have a PHPUnit test, and found this code within a function. global $argv, $argc; echo $argc; print_r($argv);

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 re开发者_C百科present (arguments passed from the command line), but I've never seen this syntax before:global $argv, $argc;

What specifically is going on here?


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


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;


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;


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

0

精彩评论

暂无评论...
验证码 换一张
取 消