How to reach "globals" from inside a class in PHP [duplicate]
Possible Duplicate:
Access global variable from within a class
I got the following code:
$foo = 'foo';
class bar
{
public function __construct()
{
var_dump($foo);
}
}
$bar = new bar();
this results in a NULL value. Is it possible to reach $foo inside the class bar? with some fancy magic word in php?
Yes, the magic word is called an argument
class bar
{
public function __construct($foo)
{
var_dump($foo);
}
}
$foo = 'foo';
$bar = new bar($foo);
You do not want the global
keyword in your code. Functions (and methods) should be isolated testable units. If you use the global keyword, you are effectively creating a dependency on the global scope inside the function scope. It is better and more maintainable to inject dependencies through arguments.
global $foo;
var_dump($foo);
See http://www.ideone.com/OOAsg.
(Why not pass an argument?)
If you are trying to access a database object there, maybe you want to have a look at the Singleton Pattern. Furthermore you may think about using a Registry:
class R {
public static $foo;
public static $db;
public static $user;
// ...
}
// later in code
R::$db = new PDO(...);
R::$user = new User();
// ...
And then you may access these variables always and from everywhere (including classes, functions and global space.)
(Okay, I know this isn't a real Registry with get
and set
methods, but I think it is enough...)
Emil - please take the advice here and DON'T get lazy on keeping your code self-contained. sure as ever, there will come a time when the system will go into a spin over back-referenced variables that are being used in a variety of ways in different parts of the program.
then there's the matter of instance instantiation. how can you reasonably keep track of the order that new classes will be called and the effect that this could have on your global var??
that and the fact that you could end up overlooking the purpose of the variable later on in development and use it for something else will just lead to a multitude of dead ends.
in a word - don't do it for the sake of your sanity in 2 months time...
jim
this is how I solved it. It really cleared all my problems
class bar
{
public static $foo;
}
$bar::foo = 'foo';
Thanks for all your answers
$foo = 'foo';
class bar
{
public function __construct()
{
// pay attention to "global"
global $foo;
var_dump($foo);
}
}
$bar = new bar();
精彩评论