为什么会出现,如果你可以将值赋给变量构造方法?(Why is there a constructor

2019-10-22 10:08发布

我刚学PHP,我感到困惑的__construct()方法的目的是什么?

如果我能做到这一点:

class Bear {
    // define properties
    public $name = 'Bill';
    public $weight = 200;

    // define methods
    public function eat($units) {
        echo $this->name." is eating ".$units." units of food... <br />";
        $this->weight += $units;
    }
}

那么,为什么有一个构造函数,而不是做呢? :

class Bear {
    // define properties
    public $name;
    public $weight;

    public function __construct(){

        $this->name = 'Bill';
        $this->weight = 200;
    }
    // define methods
    public function eat($units) {
        echo $this->name." is eating ".$units." units of food... <br />";
        $this->weight += $units;
    }
}

Answer 1:

由于构造函数可以做的比您可以在变量初始化做什么更复杂的逻辑。 例如:

class Bear {
  private $weight;
  private $colour;

  public __construct($weight, $colour = 'brown') {
    if ($weight < 100) {
      throw new Exception("Weight $weight less than 100");
    }
    if (!$colour) {
      throw new Exception("Colour not specified");
    }
    $this->weight = $weight;
    $this->colour = $colour;
  }

  ...
}

构造函数是可选的,但可以执行任意代码。



Answer 2:

你可以给动态变量到类:

有:

public function __construct(name, amount){

    $this->name = name;
    $this->weight = amount;
}

您可以使用类“法案”和“乔”和使用量的不同值。

你也可以确保你班上总是会拥有所有需要,例如工作数据库连接:你应该构造需求总是所有的需求:

public function __construct(database_connection){
[...]
}


文章来源: Why is there a constructor method if you can assign the values to variables?