Irfan
Irfan

Reputation: 5062

Why do we need function_exists?

Why do we need to check function_exists for user defined functions? It looks ok for internal or core PHP functions but if user know and defined a function himself then why do need to check for its existance?

Below is custom user defined function

if( !function_exists( 'bia_register_menu' ) ) {
    function bia_register_menu() {
        register_nav_menu('primary-menu', __('Primary Menu'));
    }
    add_action('init', 'bia_register_menu');
}

Thanks

Upvotes: 5

Views: 1482

Answers (5)

Arild
Arild

Reputation: 714

This answer on the Wordpress StackExchange clarifies why you should sometimes use if function_exists around a function declaration in a theme:

The if function_exists approach allows for a child theme to override the function definition by simply defining the function themselves. Since child theme's functions.php files load first, then they will define the function first and the parent's definition will not get loaded.

I suppose it's analogous to the protected keyword in object oriented languages.

However I still wonder whether there would be any need for it around function declarations in plugins.

Upvotes: 2

RRikesh
RRikesh

Reputation: 14401

To make sure you don't register the same function twice, which will cause an error.

You also use if(function_exists('function_name')) when you are calling functions defined in plugins. In case you deactivated your plugin, your site will still be functional.

Upvotes: 3

Benz
Benz

Reputation: 2335

Imagine that you use you're URL to get the function name and call it. Then we have the following info:

url: http://mysite.com/my/page/

When converting this url into a function name, you would do something like this:

implode('_', $myUrlPart); //my_page

The output would be "my_page" as string. But if you call this right away and the function does not exist, an error will be shown. This is where the function_exists comes in, take a look:

if (function_exists($function_name)) {
    $function_name();  //the function is called
} else {
    //call other function to show HTTP 404 page or something like that
}

Does this makes it a little clearer?

Upvotes: 0

Jani Hartikainen
Jani Hartikainen

Reputation: 43253

Because WordPress is designed so poorly it does not have any proper mechanism for autoloading modules like that, so you need to add safeguards.

Upvotes: -1

user2021438
user2021438

Reputation:

In dynamically loaded files using autoloaders, the file containing the function or class might not have loaded, so you need to check if it exists

Upvotes: 1

Related Questions