W3docs

Calling other function in the same controller?

In PHP, you can call a function within the same controller by simply calling the function name followed by parentheses.

In PHP, you can call a method within the same controller by using $this-> followed by the method name and parentheses. For example, if you have a method called foo(), you can call it within the same class like this:

Example of calling a method within the same controller in PHP

$this->foo();

If you need to call logic from another controller, modern PHP uses autoloading (via Composer) instead of manual include or require statements. However, directly instantiating controllers is considered an architectural anti-pattern in MVC frameworks. Instead, shared logic should be extracted into a dedicated service class, which can then be instantiated or injected via the framework's dependency injection container. For example:

Example of calling a method from a different controller in PHP

<?php

namespace MyApp\Services;

class FooService
{
  public function foo()
  {
    // Do something
  }
}

💡 Watch a video course Learn object oriented PHP

To call the foo() method from a service class, you can use the following code:

Example of calling a method from a different controller by instantiating the class in PHP

use MyApp\Services\FooService;

$foo = new FooService();
$foo->foo();

Note: If the method is defined as static, you can call it directly on the class using FooService::foo(); without creating an instance. However, static methods in controllers are also discouraged for business logic; prefer instance methods in service classes.