简体   繁体   中英

PHP basic (noobish) concept question: Constant vs. Function

I have a global "functions.php" file containing functions used throughout my site.

In terms of performance, efficiency, etc – is it better to call one of these functions directly or to define them as constants and call the constant instead? (Or does it matter at all?)

ie

<?php echo site_root(); ?>

vs.

<?php echo SITEROOT; ?>

Thanks

It depends on what site_root() does exactly.

  • If all it does is something very simple like read from an array and return a string, it doesn't matter whether you use the function, or a constant. Use whatever works best for you.

  • If the function does something expensive like a database lookup, it is indeed wise to do the call only once, store the result in a constant, and use that in the code.

Adam, another option is to use static vars as a cache inside a function:

function site_root() {
    static $result = null;
    if (!is_null($result)) {
         return $result;
    }
    // code for defining and returning result only once
}

You can use constants only when your code always require them. And if your code use it only here or there, then don`t use them, as code, that will define them will slow down your main code.

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