note 110163 modified in function.function-exists by aharvey
| From: | aharvey@php.net | Date: | Wed, 26 Sep 2012 00:35:40 +0000 |
| Subject: | note 110163 modified in function.function-exists by aharvey | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-191021@lists.php.net to get a copy of this message | ||
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() Other comments here about this (referencing user
"eddiec") are mostly correct. Any oddities are probably due to the order in which
you include/require files.
--was--
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 [b]true[/b] 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()
Other comments here about this (referencing user "eddiec") are mostly correct. Any
oddities are probably due to the order in which you include/require files.
http://php.net/manual/en/function.function-exists.php