Use external variable inside PHP class

前端 未结 2 1884
南旧
南旧 2021-01-05 00:48

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. Her

2条回答
  •  甜味超标
    2021-01-05 01:18

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

提交回复
热议问题