note 110163 added to function.function-exists
| From: | kitchin | Date: | Tue, 25 Sep 2012 12:49:39 +0000 |
| Subject: | note 110163 added to function.function-exists | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-191013@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 [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.
----
Server IP: 69.147.83.199
Probable Submitter: 74.4.243.172
----
Manual Page -- http://www.php.net/manual/en/function.function-exists.php
Edit -- https://master.php.net/note/edit/110163
Del: integrated -- https://master.php.net/note/delete/110163/integrated
Del: useless -- https://master.php.net/note/delete/110163/useless
Del: bad code -- https://master.php.net/note/delete/110163/bad+code
Del: spam -- https://master.php.net/note/delete/110163/spam
Del: non-english -- https://master.php.net/note/delete/110163/non-english
Del: in docs -- https://master.php.net/note/delete/110163/in+docs
Del: other reasons-- https://master.php.net/note/delete/110163
Reject -- https://master.php.net/note/reject/110163
Search -- https://master.php.net/manage/user-notes.php