Skip to content

Instantly share code, notes, and snippets.

@mohammadhzp
Last active May 22, 2022 08:13
Show Gist options
  • Save mohammadhzp/c4c87352852515f4ad74f3a75d52264c to your computer and use it in GitHub Desktop.
Save mohammadhzp/c4c87352852515f4ad74f3a75d52264c to your computer and use it in GitHub Desktop.
get_instance in codeigniter 4
# 1- Make a helper file and put following code in there
# 2- Auto-load it
# 3- call `register_ci_instance($this)` at the very beginning in your base controller
# 4- use `$ci = &get_instance()` anywhere you want. FYI: I'm not sure if `&` is even necessary when calling `get_instance`.
# Also, you may change `\App\Controllers\BaseController` for better IDE autocomplete support.
# Tested on PHP8
<?php
$CI_INSTANCE = []; # It keeps a ref to global CI instance
function register_ci_instance(\App\Controllers\BaseController &$_ci) {
global $CI_INSTANCE;
$CI_INSTANCE[0] = &$_ci;
}
function &get_instance(): \App\Controllers\BaseController {
global $CI_INSTANCE;
return $CI_INSTANCE[0];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment