Check if a PHP function exists

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 ;).

Josh Sherman - The Man, The Myth, The Avatar

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.


If you found this article helpful, please consider buying me a coffee.