note 33827 modified in function.function-exists by danbrown
| From: | danbrown@php.net | Date: | Sat, 19 Jul 2008 20:53:36 +0000 |
| Subject: | note 33827 modified in function.function-exists by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-141730@lists.php.net to get a copy of this message | ||
This can be used to conditionally define a user function. In this sense, it can act as a sort of
inline include_once().
For example, suppose you have a function A that calls function B. B is only used inside function A
and is never called from anywhere else in the script. It's logical (and perfectly legal in PHP)
to define B inside of A's definition, like so:
<?php
function A($inputArray)
{
if (!function_exists('B'))
{
function B($item)
{
// Do something with $item
// and return result
return $result;
}
}
foreach ($inputArray as $nextItem) $outputArray[] = B($nextItem);
return $outputArray;
}
?>
Without the function_exists test, you would get a fatal error the second time you called A, as PHP
would think you were trying to redefine B (not legal in PHP). The placement of the test is also
important. Since the if block is executed sequentially, like any other block of code, it must come
before any call to the function defined within.
--was--
This can be used to conditionally define a user function. In this sense, it can act as a sort of
inline include_once().
For example, suppose you have a function A that calls function B. B is only used inside function A
and is never called from anywhere else in the script. It's logical (and perfectly legal in PHP)
to define B inside of A's definition, like so:
function A($inputArray)
{
if (!function_exists('B'))
{
function B($item)
{
// Do something with $item
// and return result
return $result;
}
}
foreach ($inputArray as $nextItem) $outputArray[] = B($nextItem);
return $outputArray;
}
Without the function_exists test, you would get a fatal error the second time you called A, as PHP
would think you were trying to redefine B (not legal in PHP). The placement of the test is also
important. Since the if block is executed sequentially, like any other block of code, it must come
before any call to the function defined within.
http://php.net/manual/en/function.function-exists.php