0

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;
2
  • I suggest $GLOBALS associative array with the name of the global variable being the key and the contents of that variable being the value of the array element. Commented Jul 24, 2011 at 18:49
  • 2
    to clarify there is no problem, I'm just wondering why I can't do it in one statement. Commented Jul 24, 2011 at 18:51

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

2 Comments

Whilst true, this merely states the facts as the OP already knows. It does not attempt to explain why these facts are so.
Simply put, "because" is not an answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.