简体   繁体   中英

Why can't i call a function before defining it in a try block in php

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM