简体   繁体   中英

Use external variable inside PHP class

I'm very new to PHP classes so forgive me if the answer is really obvious. I'm trying to figure out how to use a variable defined outside of a class inside of a class. Here is a very crude example

$myVar = 'value';

class myClass {
  private $class_var = $myVar;
  //REST OF CLASS BELOW
}

I know the above doesn't work, but how can I use the external $myVar inside the class?

Try this:

$myVar = 'value';

class myClass {
  private $class_var;

  public function __construct($myVar) {
    $this->class_var=$myVar;
  }

  //REST OF CLASS BELOW
}

When declaring the class, you will need to pass $myVar like so, $myClass = new myClass($myVar); .

Every function has its own "scope". You can override that by declaring a variable as global inside the function like this:

$myVar = 'value';

class myClass {
  public function __construct() {
    global $myVar;
    $this->class_var=$myVar;
  }
}

this will set variable in the object instance.

However be advised that you can directly use it in functions without the need to set it as class variable like this:

$myVar = 'value';

class myClass {
  public function myfunction() {
    global $myVar;
    echo $myVar;
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM