-3

So I stumbled upon something I didn't realise: call_user_func_array apparently interrupts the code, but doesn't get back to finishing the rest of it! In other words, it works as if to return, break or exit the current function it was called from, ignoring all code that follows.

class B {
    function bar($arg1, $arg2) {
        $result = "$arg1 and $arg2";
        echo "Indeed we see '$result'.<br>\n";
        return $result;
    }
}

class A {
    function foo() {
        $args = ['apples', 'oranges'];
        echo "This line executes.<br>\n"
        $result = call_user_func_array(['B', 'bar'], $args);
        echo "This line never executes.<br>\n";
        echo "Thus we won't be able to use the phrase '$result' within this function.<br>\n";
    }
}

How can we return to and finish the rest of foo?

Matt
  • 162
  • 1
  • 8
  • You've got a handful of problems with this code which mean it can't run as you've currently posted it (scope issues, a syntax error, and a deprecation warning), but there's nothing wrong with the execution flow once those are fixed: https://3v4l.org/I991I . Please post a reproducible version of the problem you're seeing, or we won't be able to help. – iainn Nov 21 '21 at 10:25
  • The Minimal Work Example wasn't exactly what I was working with, which had the error. It seems `call_user_func_array` does not behave the way I explained above. It's just that my `bar` function in my actual code had a problem. I'm dealing with a lot of code, and I'm not sure exactly what I did – but the idea is that I fixed the code in whatever function I was calling. I think we can safely close this question. :) – Matt Nov 21 '21 at 11:00

1 Answers1

1

I had to make some changes to your code to actually make it work.

class B {
    static function bar($arg1, $arg2) {
        $result = "$arg1 and $arg2";
        echo "Indeed we see '$result'.<br>\n";
        return $result;
    }
}

class A {
    static function foo() {
        $args = ['apples', 'oranges'];
        echo "This line executes.<br>\n";
        $result = call_user_func_array(['B', 'bar'], $args);
        echo "This line never executes.<br>\n";
        echo "Thus we won't be able to use the phrase '$result' within this function.<br>\n";
    }
}

A::foo();

But after that it returned:

This line executes.<br>
Indeed we see 'apples and oranges'.<br>
This line never executes.<br>
Thus we won't be able to use the phrase 'apples and oranges' within this function.<br>

See: PHP Fiddle

Please provide an example that does what you say it does.

KIKO Software
  • 15,283
  • 3
  • 18
  • 33
  • Sorry! I ran into this problem in my code and tried to recreate a Minimal Work Example to post on here. I think the problem wasn't `call_user_func_array` after all – it was inside the `bar` function something broke (again, the MWE is not the exact code I was working with). It works like you say it does. My bad. :) – Matt Nov 21 '21 at 10:55