Let’s use json_encode
as an example here. Prior to PHP 5.2.0 JSON support was only available via a PECL extension and since 5.2.0 it’s been available as part of the PHP core. You could check that the server is running PHP 5.2.0 or above, but that could result in a false positive because the server could be running 5.0 and have the aforementioned PECL extension installed. A better solution is to check that the function exists via the function_exists()
function:
if (function_exists('json_encode'))
{
$json = json_encode($value
}
else
{
throw new Exception('The function json_encode() is not available.'
}
The function_exists()
function can be used to check for the existence of both internal PHP functions as well as user defined functions. Not included would be checking if a class function exists (I’ll save that for another post ;).