Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP calling a function in function_exists

Tags:

function

php

If I use function_exists as following:

if ( ! function_exists( 'get_value' ) ) :
    function get_value( $field ) {
    ..
    return $value;
}
endif;

Now, when I call the function in the same file before the above function, it will give fatal error:

Fatal error: Call to undefined function get_value() ...

But, if i call it after the above function, it will return the value without any error.

Now, if I remove the function_exists condition, ie:

function get_value( $field ) {
    ..
    return $value;
}

Then it will work if i call this function before or after in the same document. Why is this so?

like image 760
user1355300 Avatar asked Sep 07 '25 09:09

user1355300


1 Answers

If you define the function directly without the if statement, it will be created while parsing / compiling the code and as a result it is available in the entire document.

If you put it inside the if, it will be created when executing the if statement and so it is not possible to use it before your definition. At this point, everything written above the if statement is executed already.

like image 105
Florian Brinker Avatar answered Sep 10 '25 10:09

Florian Brinker