user1355300
user1355300

Reputation: 4987

PHP calling a function in function_exists

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?

Upvotes: 4

Views: 2768

Answers (2)

J.K.A.
J.K.A.

Reputation: 7404

You are calling the function before declaring it thats why it showing error. Declare you function above the IF statement, something like:

function get_value(){
//your statements
}

and write

if(condition){
//your statements
}

Upvotes: 0

Florian Brinker
Florian Brinker

Reputation: 735

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.

Upvotes: 6

Related Questions