简体   繁体   English

在PHP类中使用外部变量

[英]Use external variable inside PHP class

I'm very new to PHP classes so forgive me if the answer is really obvious. 我是PHP新手,所以如果答案非常明显,请原谅我。 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? 我知道上面的方法不起作用,但我如何在类中使用外部$ myVar?

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); 在声明类时,你需要像这样传递$myVar$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;
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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