0

When I call a function inside try block before defining. it gives me fatal error

What I was trying to do is this

try {
   echo someFunction();
   function someFunction()
   {
     return 'hello';
   }
 } catch (Exception $e ){
    return $e->getMessage();
 }

Although I just fix this just paste function above the try block I am curious what is wrong here should not it work. it is not inside in conditional block.

Yuankun
  • 6,875
  • 3
  • 32
  • 34
Amit Bisht
  • 329
  • 3
  • 15
  • Possible duplicate of [Is it possible in PHP to prevent "Fatal error: Call to undefined function"?](https://stackoverflow.com/questions/7116995/is-it-possible-in-php-to-prevent-fatal-error-call-to-undefined-function) – qskane Apr 28 '18 at 03:30

1 Answers1

0

When a function is defined in a conditional manner it's definition must be processed prior to being called. Just switch the echo and function like below.

try {
    function someFunction()
    {
        return 'hello';
    }
    echo someFunction();
} catch (Exception $e ){
    return $e->getMessage();
}

http://php.net/manual/en/functions.user-defined.php

RedElement
  • 103
  • 8