0

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; }.

Alex
  • 9,215
  • 8
  • 39
  • 82

1 Answers1

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