如果可以将值赋给变量,为什么还有构造函数方法?

时间:2010-05-29 04:08:33

标签: php oop class constructor

我只是在学习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;
    }
}

2 个答案:

答案 0 :(得分:3)

因为构造函数可以执行比变量初始化更复杂的逻辑。例如:

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

  ...
}

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

答案 1 :(得分:0)

您可以为您的班级提供动态变量:

使用:

public function __construct(name, amount){

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

您可以将您的班级用于“账单”和“乔”,并使用不同的金额值。

此外,您可以确保您的类始终具有所需的全部内容,例如工作数据库连接:构造函数应始终要求所有需求:

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