Why do we need functions?

Why do we need to check function_functions for UDFs? It looks ok for internal or core PHP functions, but if the user knows and defines the function himself, then why check for its existence?

Below custom function is configured

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

      

thank

+3


source to share


5 answers


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



You also use if(function_exists('function_name'))

when you call functions defined in plugins. If you've disabled your plugin, your site will still function.

+3


source


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



0


source


Imagine you are using a url to get the name of a function and call it. Then we get the following information:

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

When converting this url to a function name, you should do something like this:

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

      

The result will be "my_page" as a string. But if you call this right away and the function doesn't exist, an error will be shown. This is where 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 simplify a little?

0


source


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 a child theme to override a function definition by simply defining the function itself. Since the child theme's functions.php files are loaded first, they define the function first, and the parent definition is not loaded.

I assume it is analogous to the keyword protected

in object oriented languages.

However, I am still wondering if it will be necessary to describe functions in plugins.

0


source


Because WordPress is so poorly designed, it doesn't have a suitable mechanism to automatically load such modules, so you need to add security measures.

-1


source







All Articles