简体   繁体   中英

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

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.

在使用自动加载器的动态加载文件中,包含该函数或类的文件可能尚未加载,因此您需要检查它是否存在

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?

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 .

因为WordPress设计得很差,所以没有任何适当的自动加载模块机制,所以你需要添加安全措施。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM