CodeIgniter Forums
Service not working - showing undefined function service() - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: CodeIgniter 4 (https://forum.codeigniter.com/forumdisplay.php?fid=28)
+--- Forum: CodeIgniter 4 Support (https://forum.codeigniter.com/forumdisplay.php?fid=30)
+--- Thread: Service not working - showing undefined function service() (/showthread.php?tid=76328)



Service not working - showing undefined function service() - webdevron - 05-04-2020

I am tying to use service in Common.php like my other projects. But do not know why this is showing me the following error.

Quote:Fatal error: Uncaught Error: Call to undefined function service() in C:\Users\...\app\Common.php:19


Codes from Config/Services.php

PHP Code:
<?php namespace Config;

use 
CodeIgniter\Config\Services as CoreServices;

require_once 
SYSTEMPATH 'Config/Services.php';

class 
Services extends CoreServices
{
 public static function 
testService$getShared FALSE )
 {
 if(!
$getShared) return new \App\Models\TestModel;
 return static::
getSharedInstance('testService');
 }



Codes from App/Common.php

PHP Code:
<?php

if(!function_exists('test')){
    function test(){
        return service('testService')->test();    // Line number 19
    }
}

echo 
test(); 

Could you please help me to solve this issue? Thanks in advance.


RE: Service not working - showing undefined function service() - vitnibel - 05-04-2020

The file App/Common.php is designed to override system functions or to create globally-available functions. Therefore, this file is included at the very beginning of the start of the framework before, for example, services are defined. Call your function in some Controller or Helper instead.

// Edit: The url of the userguide have changed.