How to create an object in constructor CodeIgniter 4?

The creation of an object of class or library is necessary to use it. And to create an object in each method of the constructor is code redundancy, so instead of it we should create an object inside the constructor only once and use it anywhere in the controller where we need to use itHow to create an object in constructor CodeIgniter 4?.
To do this, firstly create a controller and create its constructor, as we have done below.
<?php namespace App\Controllers; 
use CodeIgniter\Controller;
use App\Libraries\Shop; // library
use App\Models\Install;

class CreateController extends Controller{
    
       public $shop;
       public $install;

  public function __construct(){
    $this->shop= new Shop();
  $this->install = new Install();
  }


    public function index(){        
   
     $data=array();
     
     $data['shop']= $this->shop;
        
        return view('create_option_set',$data);
    }
}
        
In the above code first we create a controller named as “CreateController” .Then we use library named “shop” and a model named “Install”. Then we declare global variable. Then we create constructor and inside it we create object of model and library and assign its object globally. And after that we use shop object in index method and pass this object into an array and then pass this array as data to view page.


How to create an object in constructor CodeIgniter 4?expoundsofttechsolution

ghb