Diego Alves
Diego Alves

Reputation: 2687

How to use constructors in php to initialize instance variables

I know that this is a common question but the questions I've seen (about 10) confused even more than I've been.

My questions are included in the code as comments.

I have a class with three fields

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

Upvotes: 0

Views: 306

Answers (3)

Plamen Nikolov
Plamen Nikolov

Reputation: 2733

It is up to you to decide what is more convenient for your \App\Model class users. Here is an example working with fixed number of properties.

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'); 

If you intend to work with dynamic number of properties, you should consider using array as parameters.

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')
);

Upvotes: 0

yoeunes
yoeunes

Reputation: 2945

the proper way to do it is like :

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");

Upvotes: 1

Vilsol
Vilsol

Reputation: 722

You were pretty close, to access the current instance variables, you need to use $this. You also need to use 2 underscores for the construct method. Other than that, treat it as just another function.

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");

Upvotes: 0

Related Questions