Igorssh
Igorssh

Reputation: 81

php global variables

I have a global variable $config, now i have a class and i want to use a value from config as a default argument for a class method like function f(var=$config['val']){} will this assignment work?

Upvotes: 2

Views: 252

Answers (2)

tamasd
tamasd

Reputation: 5923

No. What I would do is to add $config as an field to the class, like this:

class MyAwesomeClass {
  public $config;

  public function f() {
    ...
  }
}

$cls = new MyAwesomeClass;
$cls->config = $GLOBALS['config'];
$cls->f();

Upvotes: 0

Pekka
Pekka

Reputation: 449783

will this assignment work?

No, it won't.

There is no way to do this automatically in the function definition.

You would have to define an empty default:

function f($var = null) {  .... }

and then fill $var with a value from your configuration array inside the method if it is null.

Upvotes: 6

Related Questions