使用构造函数设置变量


Using a constructor to set variables

使用PHP类函数时,如何使用if语句在构造函数中设置变量。

我的目标是检查发送到类对象的变量,然后使用if语句在构造函数中更改它。其想法是,它可以用于其他功能。

例如:

class myClass {
    // sent variable
    public $variable;
    public function __construct($variable) {
      if($variable == 'bar') {
         $this->$variable = "foo";
      }
      else {
         $this->$variable = "bar";
      }
    }
    public function run() {
         return $variable;
    }
}

$class = new myClass("bar");
$run = $class->run();
// This should return foo
var_dump($run);

问题是,当我运行这个时,当我var_dump((时,我会得到"NULL"。不过我期待着得到"foo"。

您的代码不正确,应该如下所示-

public function __construct($variable) {
  if($variable == 'bar') {
     $this->variable = "foo";
  }
  else {
     $this->variable = "bar";
  }
}

您一直在使用

$this->$variable = "foo";

要将您需要做的成员变量引用为

$this->variable_name (without $)

因此,所有使用了上述语法的函数都需要更正。

public function run() {
     return $variable;
}

应该是

public function run() {
     return $this->variable;
}