4

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?

2
  • bcoz u are are calling it before declaring it Commented Jul 10, 2012 at 9:35
  • place function at the top of file, and call after, the problem is that function definition inside wont want make available the function until execution reaches if Commented Jul 10, 2012 at 9:35

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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
}

1 Comment

OP is well aware of this, his question is more about the case with function declaration inside an if statement.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.