Alex
Alex

Reputation: 9265

Bring a global into a class

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

Upvotes: 0

Views: 52

Answers (1)

Nick Coons
Nick Coons

Reputation: 3692

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.

Upvotes: 1

Related Questions