How to Check if Your PHP Function Exists Programming 25 JUL 2013

green php elephants - elephpantsA good way to get your PHP code to break is to reference a function that doesn’t exist (to be fair, this method of breaking code is probably valid in just about any programming language!). Luckily for us, PHP makes it fairly trivial to check that a function name does in fact exist by giving us the handy function_exists, well… function.

Basically, given a function name as a string parameter, function_exists checks the list of defined functions, both built-in (internal) and user-defined, and returns a boolean true if it finds the corresponding function.

If you then combine this function with a bit of eval magic, well then conditional function firing just got pretty easy:

function test1($message){
    echo '<p>test 1: ' . $message . '</p>';

function test2($message,$bold = false){
    echo '<p>test 2: ' . (($bold == false)?$message:"<strong>$message</strong>") . '</p>';

$function = 'test1';
$message = 'hello 1!';

if (function_exists($function)){

$function = 'test2';
$message = 'hello 2!';
$options = true;

if (function_exists($function)){


UPDATE: Actually, instead of using the always alluring but dangerous eval to run your function, it’s probably a whole lot safer, easier, and a lot less messy, just to use PHP’s built in and very handy call_user_func function.

Meaning that now our example would look like this:

function test3($message,$strings){
    echo '<p>test 3: ' . $message . '</p>';
    echo '<pre>';
    echo '</pre>';

$function = 'test3';
$message = 'hello 3!';
$options = array('line 1','line 2','line 3');

if (function_exists($function)){

Much better.

Related Posts:

About Craig Lotter

Software developer, husband and dad to two little girls. Writer behind An Exploring South African. I don't have time for myself any more.