vincej's avatar
Level 15

How Best to use a Constructor to create and pass a properties

I want to have specific properties available for use within all my methods without having to replicate the code in each and every method. So.. I'm thinking perhaps putting the code into the constructor is the way to go.

It might not be as it is not working as expected. PHPStorm is has greyed out the $contractor variable within the constructor telling me that it is not in use anywhere. Yet the $contractor variable within the Index method is not greyed out. Nevertheless, I do not get the $contractor variable for use in Index().

Many thanks for your thoughts, and corrections !

class AccountController extends Controller
{

protected $contractor;
protected $email;
protected $id;

public function __construct(Contractor $contractor,Auth $id){


            $this->id=Auth::id();
            $user = User::find($this->id);
            $contractor = Contractor::where('email', '=', $user->email)->get();

}


public function index($contractor) // THIS DOES NOT WORK
    {

    return View('contractor_portal/account_show',compact('contractor' ));
    }
}

0 likes
5 replies
bobbybouwmann's avatar
Level 88

You can't do that, because you assign it in the class itself, you can however do something like this

public function index()
{
    $contractor = $this->contractor;

    return View('contractor_portal/account_show',compact('contractor' ));
}

You might want to look at view composers instead

vincej's avatar
Level 15

@bobbybouwmann

Thanks for your rapid reply. I tried your suggestion and it worked great. No more reward points I'm afraid, but i will mark your answer as correct !

View Composers - I guess this is a new 5.1 feature which I have not learned yet. I will check it out.

Heel veel bedankt !

jimmck's avatar

@vincej Hey, not totally sure of your use case. You may want a trait. You define a set of methods to operate on a given Contractor object. You set he trait to a specific Contractor or make the trait generic to a given group Contractor like objects. e.g. Contractor, Plumber etc...

http://php.net/manual/en/language.oop5.traits.php

You create static/non static properties in the trait, just watch for namespace collisions.

bobbybouwmann's avatar

@jimmck I can't use a trait for this. A trait is only for functions. Even if you could do variables you still can't access them in your own function since the variable belongs to scope of the class and not of the function!

Please or to participate in this conversation.