0

I am studying a friend's project and I'm confused why he use parent::__construct($model) and $this->model = $model at the same time in CategoryRepository.php. Could someone help me understand what's the difference of the two please?

I've already been to these links PHP Codeigniter - parent::__construct, A __construct on an Eloquent Laravel Model but I want a more specific answer correlating to the code below.


Here is the code of CategoryRepository.php

class CategoryRepository extends BaseRepository implements CategoryContract
{
    public function __construct(Category $model)
    {
        parent::__construct($model);
        $this->model = $model;
    }
}

BaseRepository.php

class BaseRepository implements BaseContract
{
    protected $model;

    public function __construct(Model $model)
    {
        $this->model = $model;
    }
}
  • From the code given there is no difference. `$this->model = $model;` is not required in `CategoryRepository` because it is being set in `BaseRepository` but it won't cause any problems. – Mark Aug 15 '20 at 10:24

1 Answers1

1

parent is a PHP keyword use call a property or method of a parent class.

So parent::__construct($model) will call the __construct method of the parent class (BaseRepository, here).

When extending a class, it is sometimes necessary to call the parent constructor, when, let's say, the parent class is also initialising some properties needed. Instead of initialising them in child class constructor, you just need to call the parent class constructor and pass to it the necessary arguments.

Now in your question, this->model = $model; is not really needed in the child constructor (constructor in CategoryRepository) because it will be already initialized when call to parent::__construct($model) and will be accessible in the child class.

this->model = $model; will actually be necessary if $model in BaseRepository was a private property. Then it will not be available in the child class CategoryRepository even if the parent constructor was called.

Prince Dorcis
  • 955
  • 7
  • 7