PHP 8.4.24 Released!

Voting

: nine minus zero?
(Example: nine)

The Note You're Voting On

kitchin
13 years ago
You can use this function to conditionally define functions, see: http://php.net/manual/en/functions.user-defined.php

For instance Wordpress uses it to make functions "pluggable." If a plugin has already defined a pluggable function, then the WP code knows not to try to redefine it.

But function_exists() will always return true unless you wrap any later function definition in a conditional clause, like if(){...}. This is a subtle matter in PHP parsing. Some examples:

<?php
if (function_exists('foo')) {
  print "foo defined\\n";
} else {
  print "foo not defined\\n";
}
function foo() {}

if (function_exists('bar')) {
  print "bar defined\\n";
} else {
  print "defining bar\\n";
  function bar() {}
}
print "calling bar\\n";
bar(); // ok to call function conditionally defined earlier

print "calling baz\\n";
baz(); // ok to call function unconditionally defined later
function baz() {}

qux(); // NOT ok to call function conditionally defined later
if (!function_exists('qux')) {
  function qux() {}
}
?>
Prints:
  foo defined
  defining bar
  calling bar
  calling baz
  PHP Fatal error: Call to undefined function qux()

Any oddities are probably due to the order in which you include/require files.

<< Back to user notes page

To Top