Error when calling methods between two services (triggered by init) I have two Services in my plugin. MyPluginService is the "main" service, and MyPlugin_OtherService accomplishes some other tasks (when it is occasionally needed).

There is an init method in MyPluginService which starts a chain of events, and under certain circumstances will call a method in MyPlugin_OtherService.

MyPluginService

public function init() {
    parent::init();
    if ("conditions are met") {
        craft()-&gt;myPlugin_otherService-&gt;methodInOtherService();
    }
}

public function methodInMainService() {
    // ...
}


MyPlugin_OtherService

public function methodInOtherService() {
    craft()-&gt;myPlugin-&gt;methodInMainService();
}


While the method in MyPlugin_OtherService is being run, it will refer back to a method in MyPluginService. This is where the error is triggered:


  Fatal error: Call to undefined method stdClass::methodInMainService()


I don't understand why it's not recognizing that call to the main service method. Hasn't the main service already been initialized before this point? There is a lot about "lazy loading" that I don't understand, maybe this falls in that knowledge gap.
Your service’s init() function gets called immediately after it is loaded – and before Yii has had a chance to remember that craft()-&gt;myPlugin should return the service instance.

Take a look at these two lines from CModule::getComponent() (the method that the magic getter invokes when you call craft()-&gt;somePluginName):

$component-&gt;init();
return $this-&gt;_components[$id]=$component;


So when MyPlugin_OtherService::methodInOtherService() tries to refer back to craft()-&gt;myPlugin, craft()-&gt;myPlugin has not yet been assigned to the service instance, which results in the PHP fatal error you’re getting.

I can propose a change that would fix this:

$this-&gt;_components[$id] = $component;
$component-&gt;init();
return $component;


…but I’m not sure what the implications would be for that.

You might just need to question whether it’s so important for this code to be running from init() as opposed to another function that you’d have to invoke manually. Having it in init() could lead to other unexpected consequences as well.