If I have a config file with $var = array('1', '2', '3');
How do I access it in a class without defining it as a constant? var $class_var = $var
doesn't work. Previously, in procedural it was a matter of function this { global $var; echo $var; }
.
Asked
Active
Viewed 48 times
0

Alex
- 9,215
- 8
- 39
- 82
-
2You really don't want to use the `global` keyword http://stackoverflow.com/questions/11923272/use-global-variables-in-a-class/11923384#11923384 – PeeHaa Aug 04 '13 at 00:46
-
1`global` is a sign of doing it wrong, regardless of what 'it' is. – Major Productions Aug 04 '13 at 01:13
1 Answers
1
There are a couple of ways. You can pull it into your construct as a global:
class myclass{
var $var;
function __construct() {
global $var;
$this->var = $var;
}
}
You can pass it as a variable when you instantiate the class:
class myclass{
var $var;
function __construct( $var ) {
$this->var = $var;
}
}
$class = new myclass( $var );
Not using globals if at all possible is generally preferred.

Nick Coons
- 3,682
- 1
- 19
- 21