如果可以将值分配给变量,为什么会有构造方法? [英] Why is there a constructor method if you can assign the values to variables?

查看:67
本文介绍了如果可以将值分配给变量,为什么会有构造方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是在学习PHP,并且对__construct()方法的用途感到困惑?

I'm just learning PHP, and I'm confused about what the purpose of the __construct() method?

如果我可以这样做:

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

然后为什么要用构造函数呢? :

Then why do it with a constructor instead? :

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


推荐答案

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

Because constructors can do more complicated logic than what you can do in variable initialization. For example:

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

  ...
}

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

A constructor is optional but can execute arbitrary code.

这篇关于如果可以将值分配给变量,为什么会有构造方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆