Hi

Is it possible to overload return() function for some part of code (ie. for the scope of some class)? I would NOT like to define separate function to do 'other stuff' and use it on every return like that: return(myFunction());

Is it possible? Maybe there is some other trick?

Thanks

Dani AI

Generated

— short answer: you cannot overload the return language construct. was right. return is part of PHP's syntax, not a function you can redefine. For background see the PHP manual on returning values: Returning values from functions.

There are practical patterns to run "other stuff" on every exit path without wrapping every return manually:

Use try...finally so cleanup always runs before the function actually returns.

function foo() {
    try {
        if ($cond) return computeA();
        return computeB();
    } finally {
        // runs on every return path
        doOtherStuff();
    }
}

Use a scope-guard object whose destructor performs the action. This gives RAII-like behavior: the guard is destroyed when the function scope ends (including when returning).

class ScopeGuard {
    private $cb;
    public function __construct(callable $cb) { $this->cb = $cb; }
    public function __destruct() { ($this->cb)(); }
}

function bar() {
    $guard = new ScopeGuard(function() { doOtherStuff(); });
    if ($x) return 1;
    return 2;
}

Cautions: avoid throwing exceptions from __destruct, and be aware destructors run only when the object is actually destroyed (if you return the guard or keep references, it may run later). If the intent is cross-cutting work (logging, metrics, cleanup), consider centralizing it with a wrapper/higher-order function or an AOP/middleware approach rather than trying to change return itself.

Recommended Answers

All 2 Replies

I'm afraid it isn't possible. But if you tell us why would you ever want such a thing maybe someone will come up with a better solution.

I'm afraid it isn't possible. But if you tell us why would you ever want such a thing maybe someone will come up with a better solution.

Thank you for your reply! :) This question was due to my little knowledge in PHP, then...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.