【问题标题】:Why is there a constructor method if you can assign the values to variables?如果可以将值分配给变量,为什么还有构造方法?
【发布时间】:2010-05-29 04:08:32
【问题描述】:

我刚学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;
    }
}

【问题讨论】:

    标签: php oop class constructor


    【解决方案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;
      }
    
      ...
    }
    

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

    【讨论】:

      【解决方案2】:

      你可以给你的班级动态变量:

      与:

      public function __construct(name, amount){
      
          $this->name = name;
          $this->weight = amount;
      }
      

      您可以将您的类用于“bill”和“joe”,并使用不同的金额值。

      你还可以确保你的类总是有它需要的一切,例如一个有效的数据库连接:你的构造函数应该总是要求所有的需求:

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

      【讨论】:

        猜你喜欢
        • 2011-01-27
        • 2023-04-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-02-10
        • 2022-10-05
        • 1970-01-01
        相关资源
        最近更新 更多