How to auto call function in php for every other function call

How to auto call function in php for every other function call

  1. Blog
  2. 15 November 2026
  3. 5 min read

Stefan Bogdanescu

Founder & Senior Architect

Intercepting Method Calls Without Modifying Signatures

The core challenge here is triggering behavior before a method executes without altering the method's internal logic or requiring every single method in your class to be manually wrapped. The naive approach of placing test1() calls at the top of every function quickly becomes unmanageable as your class grows. You need a mechanism that observes the call stack or intercepts the execution flow globally for that object instance.

In PHP, there are two primary architectural patterns to solve this: using a Trait to inject the interceptor logic into the class, or implementing a Proxy Pattern (often via Magic Methods) to wrap the object itself. Both achieve the goal of running test1 before other methods, but they differ significantly in where the logic lives and how it is invoked.

The Trait Approach: Centralized Logic

The most "native" PHP way to handle this without changing your class structure is using a Trait. A Trait allows you to define shared method functionality that can be mixed into any number of classes.

You can create a generic Interceptor trait that defines the pre-execution hook. By placing the call to test1() inside this trait, you ensure it runs whenever any public method on the class is invoked, provided the trait is applied.

trait Interceptor {
    // Define the function that runs before others
    protected function runBeforeExecution() {
        echo 'test1';
    }
}

class Test implements Interceptor {
    use Interceptor;

    public function test2() {
        $this->runBeforeExecution();
        echo 'test2';
    }

    public function test3() {
        $this->runBeforeExecution();
        echo 'test3';
    }
}

While this works, it requires manually calling $this->runBeforeExecution() inside every single method. This violates the spirit of "auto-call." To make it truly automatic without modifying the target methods' bodies, you would need to override __call or use a proxy, which leads us to the next, more robust solution.

The Proxy Pattern with Magic Methods

If you cannot modify the definitions of test2 and test3, or if you want the interception logic to be completely decoupled from the business logic inside those methods, the Magic Method approach is the standard industry practice.

By implementing __call() and __callStatic(), PHP allows you to intercept calls to undefined methods. However, in this specific scenario, we know the methods exist (like test2), so we need a slightly different twist: we need to wrap the existing logic or use a static helper that executes before the actual method call.

A cleaner implementation for "calling before any function" often involves defining a dedicated entry point or using a wrapper class that delegates to the original object. However, if you strictly require modifying the behavior of an existing instance without changing its source code, Traits combined with a specific design pattern is usually preferred.

Here is a more advanced implementation using a Trait-based interceptor that doesn't require editing every method body, assuming we can define a generic entry point:

trait PreExecutionHandler {
    public function __call($method, $parameters) {
        // Execute the pre-function logic first
        echo 'test1';
        
        // Then call the original intended method
        return $this->$method(...$parameters);
    }
    
    // Note: This only works for undefined methods. 
    // If test2 and test3 are defined, __call is ignored unless we override them or use reflection.
}

The limitation of __call above is that it only triggers when a method is not found in the class. Since test2 and test3 exist, PHP will execute them directly, bypassing __call.

The Reflection Solution

To truly intercept calls to defined methods without modifying their bodies, you must use Reflection. You can create a wrapper that uses Reflection to invoke methods dynamically or override the behavior by injecting a proxy.

However, the most pragmatic and widely accepted solution in PHP frameworks (like Laravel) for this specific requirement—running code before any action—is often handled via Service Facades or Event Dispatching, rather than raw class manipulation.

If you are building an application where this pattern is critical, consider using a dependency injection container or a service locator that wraps your Test object in a proxy. The proxy holds the original instance and delegates calls to it while executing test1 first. This keeps your domain classes clean (no magic methods or reflection hacks) and allows you to swap the implementation easily later.

class TestProxy {
    private $target;
    
    public function __construct(Test $target) {
        $this->target = $target;
    }

    public function test2() {
        echo 'test1'; // Pre-execution
        return $this->target->test2();
    }

    public function test3() {
        echo 'test1'; // Pre-execution
        return $this->target->test3();
    }
}

While this requires defining the proxy methods, it is significantly more maintainable than using Reflection to force intercepts on every single method. It also avoids the pitfalls of __call logic becoming a "god method" that tries to handle everything generically.

Why Not Just Use __call?

Many developers jump to __call() first because it sounds like a universal interceptor. However, __call is specifically designed for undefined methods (e.g., $obj->unknownMethod()). If the class defines test2, PHP ignores __call. To make __call work for defined methods, you would have to explicitly declare those methods as "undefined" or use Reflection to bypass the standard resolution order, which introduces significant overhead and complexity.

Conclusion on Approach

For your specific requirement of auto-calling test1 before any other function:

  1. If you can edit the class: Use a Trait combined with a consistent naming convention for entry points, or simply refactor to use a Proxy wrapper.
  2. If you cannot edit the class: You must wrap the object in a facade/proxy that exposes the methods but prepends the logic.

The Proxy pattern is generally the most robust solution. It isolates the side-effect logic (test1) from the core business logic, making the code easier to test and understand. In larger frameworks like Laravel, this pattern is often abstracted into Event Listeners or Service Providers, ensuring that cross-cutting concerns are handled declaratively rather than through procedural interception hacks.

Our network