开发者

PHP global variable inside class function

开发者 https://www.devze.com 2023-03-23 01:41 出处:网络
How come inside a function which is inside a class, I can\'t do this statement: global $connected = true;

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;
$conn开发者_开发知识库ected = 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.

0

精彩评论

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