Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

tprod's avatar
Level 2

Conflict between Trait constructor and Controller constructor

Hi,

I use a PaymentGateway Trait which has a constructor here :

public function __construct()
    {
        $this->mangoPayApi = new \MangoPay\MangoPayApi();
        $this->mangoPayApi->Config->ClientId = config('services.mangopay.key');
        $this->mangoPayApi->Config->ClientPassword = config('services.mangopay.secret');
        $this->mangoPayApi->Config->TemporaryFolder = public_path();
    }

I use it in my controller which has a constructor too when I use a middleware like this :

use MangoPay;

    public function __construct()
    {
        $this->middleware('premium');
    }

How can I use both ? How can I do ? I'm using Laravel 5.4.

0 likes
2 replies
FarhadMohammadi's avatar

You can not use constractor in Trait, the traits in php use for multiple inheritence but the constractor belongs to class, not traits. My advice, based on over a year of dealing with traits in PHP, is: avoid writing constructors in traits at all, or if you must - at least make them parameterless. Having them in traits goes against the idea of constructors in general, which is: constructors should be specific to a class to which they belong. Other, evolved high-level languages don't even support implicit constructor inheritance. This is because constructors have far more stronger relation to the class then other methods.

2 likes
Robstar's avatar

Surely you'd use a custom service provider here?

Please or to participate in this conversation.