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?
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?
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.
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.