如何在php中使用构造函数来初始化实例变量

时间:2017-08-28 15:09:27

标签: php oop

我知道这是一个常见问题,但我见过的问题(大约10个)比我以前更加困惑。

我的问题作为评论包含在代码中。

我有一个有三个字段的课程

public class Model
{
    public $prop1;
    public $prop2;
    public $prop3;

     public function _construct($params)  // doubt 1: Do I have to pass an array to a constructor, can't I pass the parameters individually
       {
                // doubt 2: How to assign the value to the instance variables
       }
}

$model = new \App\Model($whatToPuthere); //doubt 3: How to provide the constructor parameters

3 个答案:

答案 0 :(得分:1)

正确的方法就是:

public class Model
{
    public $prop1;
    public $prop2;
    public $prop3;

     public function __construct($prop1, $prop2, $prop3)  
     {
          $this->prop1 = $prop1; 
          $this->prop2 = $prop2; 
          $this->prop3 = $prop3; 
     }
}

$model = new \App\Model("prop1_value", "prop2_value", "prop3_value");

答案 1 :(得分:0)

您非常接近,要访问当前的实例变量,您需要使用$this。您还需要为构造方法使用2个下划线。除此之外,将其视为另一种功能。

class Model {

    public $prop1;
    public $prop2;
    public $prop3;

    public function __construct($prop1, $prop2, $prop3) {
        $this->prop1 = $prop1;
        $this->prop2 = $prop2;
        $this->prop3 = $prop2;
    }

}

$model = new \App\Model("prop1", "prop2", "prop3");

答案 2 :(得分:0)

由您决定哪些方便您的\App\Model班级用户。以下是使用固定数量属性的示例。

class Model
{
    public $prop1;
    public $prop2;
    public $prop3;

     public function __construct($prop1, $prop2, $prop3)
     {
       $this->prop1 = $prop1;
       $this->prop2 = $prop2;
       $this->prop3 = $prop3; 
     }
}

$model = new \App\Model('Property 1', 'Property 2', 'Property 3'); 

如果您打算使用动态数量的属性,则应考虑使用数组作为参数。

class Model
{
    public $prop1;
    public $prop2;
    public $prop3;

     public function __construct(array $properties)
     {
         $this->prop1 = $properties['prop1'];
         $this->prop2 = $properties['prop2'];
         $this->prop3 = $properties['prop3']; 
     }
}

$model = new \App\Model(
   array('prop1' => 'Property 1', 'prop2' => 'Property 2', 'prop3' => 'Property 3')
);
相关问题