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; ?开发者_如何学Go>
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.
精彩评论