简体   繁体   中英

PHP global variable inside class function

How come inside a function which is inside a class, I can't do this statement:

global $connected = true;

But I can do this:

global $connected;
$connected = true;

The bringing of $connected into scope, and the assignment of a value to it, are two separate things.

There is no reason for them to be possible in one statement, which wouldn't really make much sense.


Does the following code:

function foo() {
   global $x = 5;
}
  • Bring the "global expression" $x = 5 into scope?
  • Bring the "global expression" 5 into scope?
  • Assign 5 to the global $x ?
  • Assign 5 to the global $x and then bring $x into scope?

I know of course that you intend for it to mean the latter, and that the first two have no meaning. But, that is not clear from the proposed statement. It would be poor syntax.

Because inside a function you first have to announce a global variable. It is something you must do in the beginning of the function. That way you can activate a certain variable which was not passed through.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM