使用构造函数设置变量

时间:2014-06-16 07:34:24

标签: php class object

使用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”。

2 个答案:

答案 0 :(得分:3)

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

public function __construct($variable) {

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

您一直在使用

$this->$variable = "foo";

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

$this->variable_name (without $)

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

答案 1 :(得分:3)

public function run() {
     return $variable;
}

应该是

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