Instantiate class in method parameter or within method

Asked

Viewed 446 times

0

Working with an Laravel controller I came across something similar to this:

public function show(Role $role)
{
// é apenas um exemplo. 
}

Where the Role class is instantiated in the variable $role within the method parameter, but I can also instantiate the class as follows:

public function show()
{
   $role = new Role();
}

Here comes my doubt, what would be the difference between these two ways of working, and the advantage between them?

  • https://coredump.pt/questions/20171048/laravel-4-inversion-of-control try reading this.

  • https://laravel.com/docs/5.7/controllers#dependency-Injection-and-controllers that is more complete

1 answer

1


Instance by parameter

This way in the place where the "show" method is executed it is necessary to pass as parameter the object "Scroll"

public function show(Role $role)
{
// é apenas um exemplo. 
}

Instantiated object in the method itself

Whereas in this way the object is already instantiated within the method itself.

public function show()
{
   $role = new Role();
}

When and how to use

The best way will depend on what you want to do, for example if you want to pass the "Scroll" object with some custom settings every time you call the "show" method you would have to use the first method, since at all times you call "show" would be necessary to pass the object "Scroll".

On the other hand if the "Role" object has the same behavior whenever it is called by the "show" method it is better to use the second method, since its definition will be the same.

  • 2

    In this case it would be the dependency injection that in Laravel makes: https://coredump.pt/questions/20171048/laravel-4-inversion-of-control give a read, to be complete... and the most complete: https://laravel.com/docs/5.7/controllers#dependency-Injection-and-controllers

  • @Virgilionovic I go a read, thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.