1

Possible Duplicate:
Global variables in PHP

I have a PHP script someting like

global $var1;

function func1() {
    $var1->something(); // $var1 not found ... why?
}

must I do global $var1 in every function?

Community
  • 1
  • 1
JM at Work
  • 2,417
  • 7
  • 33
  • 46
  • 2
    seriously, do you guys ever search **before** asking your question like you are asked to do in http://stackoverflow.com/questions/ask-advice. The same thing was asked just 9 hours ago and that was a duplicate of many already as well. Please do your homework before asking. – Gordon Mar 31 '11 at 07:06

2 Answers2

4

must I do global $var1 in every function?

Yes.

Functions in PHP get their own variable scope. The only way to gain access to variables in the global scope is to request them directly.

I'm sure you'll understand how this can cause difficult-to-read spaghetti code. Avoid globals whenever you can.

If you are building OO code, consider a Registry (a namespaced collection) and/or Dependency Injection (passing objects required by a new object in the constructor) instead.

Charles
  • 50,943
  • 13
  • 104
  • 142
  • 4
    I'd rather call the Registry a namespaced Global, because that's what it is if you access it statically. Same problems as just using `$GLOBALS` or import an array with `global` keyword. See http://stackoverflow.com/questions/5283102/how-is-testing-registry-pattern-or-singleton-hard-in-php/5283151#5283151 – Gordon Mar 31 '11 at 07:10
1

It is the other way around.

$var1 = new StdClass();

function func1() {
    global $var1
    $var1->something(); // $var1 not found ... why?
}
`

Yes indeed you need to call it this way in the every function you declare.

J Bourne
  • 1,409
  • 2
  • 14
  • 33