简体   繁体   English

PHP基本(讨厌)概念问题:常量与函数

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

I have a global "functions.php" file containing functions used throughout my site. 我有一个全局“ functions.php”文件,其中包含在我的网站上使用的所有功能。

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. 这取决于site_root()确切功能。

  • 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. 而且,如果您的代码仅在此处或此处使用它,则不要将它们用作代码,因为它将定义它们会降低您的主代码的速度。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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